2015-02-09 151 views
0

停止Python腳本,我想知道是否有一種編程停止python腳本執行而不殺死進程像我們做這個代碼的方式:而不殺死Python進程

import sys 
sys.exit() 

這將是代碼相當於按Ctrl + C

+0

如果 「停止」 你的意思是 「暫停,後面繼續的可能性」,嘗試的raw_input''或'進口PDB( 「按回車鍵繼續。」); pdb.set_trace()'。 – Kevin 2015-02-09 15:23:14

+4

'Ctrl + C'拋出一個'KeyboardInterrupt'異常,如果沒有被捕獲,則會終止該過程。所以我不確定'sys.exit'應該有多大的不同。 – 2015-02-09 15:25:22

+0

此外,Python是一種解釋型語言,這就是爲什麼停止執行腳本意味着停止執行解釋器 – ForceBru 2015-02-09 15:26:44

回答

5

定義自己的異常,

class HaltException(Exception): pass 

包裹腳本
try: 
    # script goes here 

    # when you want to stop, 
    raise HaltException("Somebody stop me!") 

except HaltException as h: 
    print(h) 
    # now what? 
+0

謝謝你理解這個問題,的確解決了這個問題 – 2015-02-09 15:38:47

+0

你也可以將你的整個代碼封裝在函數中(不要忘記main()和if __name__ =='__main__'stuff),那麼當你想退出時,返回一個隨機值 – 2015-02-09 15:39:35

2

這是我發現的工作 - 停留在解釋器中,同時停止腳本。

# ------------------------------------------------------------------ 
# Reset so get full traceback next time you run the script and a "real" 
# exception occurs 
if hasattr (sys, 'tracebacklimit'): 
    del sys.tracebacklimit 

# ------------------------------------------------------------------ 
# Raise this class for "soft halt" with minimum traceback. 
class Stop (Exception): 
    def __init__ (self): 
     sys.tracebacklimit = 0 

# ================================================================== 
# ... script here ... 
if something_I_want_to_halt_on: 
    raise Stop() 

# ... script continues ... 
2

我在開發Sublime Text包時遇到了這個問題。我試圖阻止一個Sublime Text Python包,在包被重新加載時測試一些東西。

如果我打電話sys.exit(),我殺死了Sublime Text python解釋器,並需要重新啓動Sublime Text。但搜索後,我想通了該解決方案是非常簡單的,我只需要調用raise ValueError(),而不是sys.exit()

import sys 
print(sys.path) 

sys.exit() 

- >

import sys 
print(sys.path) 

raise ValueError() 

這將停止python腳本執行權後運行print(sys.path)。雖然它會打印一個大堆棧跟蹤。但是,如果你raise ValueError()前添加指令sys.tracebacklimit = 1,可以減少堆棧跟蹤呼叫一行:

import sys 
print(sys.path) 

raise ValueError() 

- >

import sys 
print(sys.path) 

sys.tracebacklimit = 1 
raise ValueError() 

相關的問題:

  1. Stop running python script without killing the interpreter
  2. Manually raising (throwing) an exception in Python
0

我重新發布從here 我的答案,因爲它應該解決您的問題,以及只要你的交互shell是IPython的。它會...

  • 不殺退出內核
  • 沒有顯示追蹤
  • 不會強迫你鞏固與嘗試/節選
  • 帶或不帶IPython的工作代碼,無需更改代碼

只需從下面的代碼中將'exit'導入到腳本中,您也可以使用IPython運行並調用'exit()'。


""" 
# ipython_exit.py 
Allows exit() to work if script is invoked with IPython without 
raising NameError Exception. Keeps kernel alive. 

Use: import variable 'exit' in target script with 
    'from ipython_exit import exit'  
""" 

import sys 
from io import StringIO 
from IPython import get_ipython 


class IpyExit(SystemExit): 
    """Exit Exception for IPython. 

    Exception temporarily redirects stderr to buffer. 
    """ 
    def __init__(self): 
     # print("exiting") # optionally print some message to stdout, too 
     # ... or do other stuff before exit 
     sys.stderr = StringIO() 

    def __del__(self): 
     sys.stderr.close() 
     sys.stderr = sys.__stderr__ # restore from backup 


def ipy_exit(): 
    raise IpyExit 


if get_ipython(): # ...run with IPython 
    exit = ipy_exit # rebind to custom exit 
else: 
    exit = exit  # just make exit importable