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

2024-04-25 17:57:24 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
Terminating a Python script

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

就像

some code

quit() # quit at this point

some more code (that's not executed)

Tags: 命令脚本thatmorescriptnotcodesome
3条回答

sys.exit()会做你想做的事。

import sys
sys.exit("Error message")

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

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

相关问题 更多 >