以编程方式停止执行python脚本?

时间:2009-02-12 21:18:06

标签: python

  

可能重复:
  Terminating a Python script

是否可以使用命令停止在任何一行执行python脚本?

some code

quit() # quit at this point

some more code (that's not executed)

4 个答案:

答案 0 :(得分:305)

sys.exit()将完全按照您的意愿行事。

import sys
sys.exit("Error message")

答案 1 :(得分:101)

你可以raise SystemExit(0)而不是给import sys; sys.exit(0)带来麻烦。

答案 2 :(得分:27)

你想要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

答案 3 :(得分:14)

exit()quit()内置函数可以满足您的需求。不需要导入sys。

或者,您可以引发SystemExit,但是您需要注意不要在任何地方捕获它(只要您在所有try ..块中指定异常类型,就不会发生这种情况。)< / p>

相关问题