我如何才能让python脚本安全地退出自身? [英] How can I have a python script safely exit itself?
问题描述
在这种情况下,如果输入错误,我必须输入密码,否则脚本将不会继续执行而仅退出自身?但是如何告诉脚本安全退出自身?
Heres the scenario I have a password that must be entered if entered wrong the script will not proceed and just exit itself? But how can I tell the script to safely exit itself?
我尝试了 sys.exit()
,但这会产生回溯错误,而且似乎不是一个非常干净的退出方法.
I tried sys.exit()
but that gives a traceback error and doesn't seem like a very clean exit method.
推荐答案
实际上, sys.exit()
只会抛出 SystemExit
异常,这将导致如果未捕获到此异常,则程序退出,但我认为它的编码不佳.
In fact, sys.exit()
will only throw a SystemExit
exception, which would make the program exit if this exception wasn't catched, but I don't think it's poor coding.
无论如何,如果您需要不惜一切代价立即退出,则另一种可能性是使用 os._exit(0)
.(请参见 http://docs.python.org/2/library/exceptions.html#exceptions.SystemExit )
Anyway, another possibility is to use os._exit(0)
if you need to exit immediately at any cost. (cf. http://docs.python.org/2/library/exceptions.html#exceptions.SystemExit)
这篇关于我如何才能让python脚本安全地退出自身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!