是否有可能在同一個命令行的任何停止python腳本的執行?
像
some code
quit() # quit at this point
some more code (that's not executed)
是否有可能在同一個命令行的任何停止python腳本的執行?
像
some code
quit() # quit at this point
some more code (that's not executed)
sys.exit()將不正是你想要的。
import sys
sys.exit("Error message")
想要sys.exit()
。從Python的文檔:
>>> import sys
>>> print sys.exit.__doc__
exit([status])
Exit the interpreter by raising SystemExit(status).
If the status is omitted or None, it defaults to zero (i.e., success).
If the status is numeric, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system
exit status will be one (i.e., failure).
所以,基本上,你會做這樣的事:
from sys import exit
# Code!
exit(0) # Successful exit
你可以raise SystemExit(0)
而不是去所有的麻煩import sys; sys.exit(0)
。
爲什麼這不是被接受的答案?有沒有理由更喜歡`import sys; sys.exit(0)`? – pela 2017-12-08 11:20:37
exit()
和quit()
內置函數只是你想要的。不需要導入sys。
或者,您可以提高SystemExit
,但您需要小心,不要在任何地方捕捉它(只要您指定所有try ...塊中的異常類型,就不會發生這種情況)。
看看爲什麼簡單的exit()不用導入就可以工作:http://docs.python.org/library/constants.html – George 2009-02-12 22:38:01
@gdivos引用這個非常相同的頁面:「它們對於交互解釋器外殼,不應該在程序中使用。「 – hop 2009-02-13 02:48:52