问题
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