How can I have a python script safely exit itself?

旧城冷巷雨未停 提交于 2021-01-27 14:38:56

问题


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.


回答1:


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.

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)




回答2:


you are using the sys module, but you haven't imported it.

add this before the sys.exit() line :

import sys


来源:https://stackoverflow.com/questions/11788651/how-can-i-have-a-python-script-safely-exit-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!