简体   繁体   English

如何让 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?但是我怎样才能告诉脚本安全退出呢?

I tried sys.exit() but that gives a traceback error and doesn't seem like a very clean exit method.我试过sys.exit()但这给出了一个回溯错误并且看起来不是一个非常干净的退出方法。

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.事实上, sys.exit()只会抛出一个SystemExit异常,如果没有sys.exit()这个异常,这将使程序退出,但我认为它不是糟糕的编码。

Anyway, another possibility is to use os._exit(0) if you need to exit immediately at any cost.无论如何,如果您需要不惜任何代价立即退出,另一种可能性是使用os._exit(0) (cf. http://docs.python.org/2/library/exceptions.html#exceptions.SystemExit ) (参见http://docs.python.org/2/library/exceptions.html#exceptions.SystemExit

you are using the sys module, but you haven't imported it.您正在使用sys模块,但您尚未导入它。

add this before the sys.exit() line :sys.exit()行之前添加:

import sys

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM