gpt4 book ai didi

python - 如何终止脚本?

转载 作者:IT老高 更新时间:2023-10-28 11:58:29 25 4
gpt4 key购买 nike

如何提前退出脚本,例如 PHP 中的 die() 命令?

最佳答案

import sys
sys.exit()

来自 sys module documentation 的详细信息:

sys.<strong>exit</strong>([<em>arg</em>])

Exit from Python. This is implemented by raising theSystemExit exception, so cleanup actions specified by finally clausesof try statements are honored, and it is possible to intercept theexit 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 isconsidered “abnormal termination” by shells and the like. Most systemsrequire it to be in the range 0-127, and produce undefined resultsotherwise. Some systems have a convention for assigning specificmeanings to specific exit codes, but these are generallyunderdeveloped; Unix programs generally use 2 for command line syntaxerrors and 1 for all other kind of errors. If another type of objectis passed, None is equivalent to passing zero, and any other object isprinted 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 whenan error occurs.

Since exit() ultimately “only” raises an exception, it will only exitthe process when called from the main thread, and the exception is notintercepted.

请注意,这是退出的“不错”方式。 @ glyphtwistedmatrix下面指出,如果你想要一个“硬退出”,你可以使用 os._exit(*errorcode*) ,尽管它在某种程度上可能是特定于操作系统的(例如,在 Windows 下它可能不会出现错误代码),而且它肯定不太友好,因为它不允许解释器在进程终止之前进行任何清理。另一方面,它确实杀死了整个进程,包括所有正在运行的线程,而 sys.exit() (如文档中所说)仅在从主线程调用时退出,没有其他线程在运行。

关于python - 如何终止脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com