终止Python脚本
时间:2020-03-05 18:56:20 来源:igfitidea点击:
我知道PHP中的die()
命令可以尽早停止脚本。
如何在Python中执行此操作?
解决方案
回答
import sys sys.exit()
sys模块文档中的详细信息:
sys.exit([arg]) Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level. The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs. Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted.
请注意,这是退出的"不错"方式。下面的@glyphtwistedmatrix指出,如果我们想要"硬退出",则可以使用os._exit(errorcode),尽管它在某种程度上可能是特定于os的(例如,在Windows下可能不会显示错误代码),并且肯定不是那么友好,因为它不允许解释器在过程终止之前进行任何清理。
回答
另一种方法是:
raise SystemExit
回答
from sys import exit exit()
作为参数,我们可以传递退出代码,该退出代码将返回给OS。默认值为0。
回答
虽然我们通常应该选择sys.exit,因为它比其他代码更"友好",但它实际上所做的只是引发一个异常。
如果我们确定需要立即退出进程,并且我们可能在某个将捕获SystemExit
的异常处理程序中,则还有另一个函数os._exit
会在C级别立即终止,并且不执行任何操作。口译员的正常拆解;例如,不执行在" atexit"模块中注册的钩子。