I try to exit a script but it doesn't exit.
Here is my code:
import sys
try:
...
print "I'm gonna die!"
sys.exit()
except:
...
print 'Still alive!'
And the results are:
I'm gonna die!
Still alive!
WHY?
You are catching the SystemExit
exception with your blanket except
clause. Don't do that. Always specify what exceptions you are expecting to avoid exactly these things.
If you really need to exit immediately, and want to skip normal exit processing, then you can use os._exit(status)
. But, as others have said, it's generally much better to exit using the normal path, and just not catch the SystemExit
exception. And while we're on the topic, KeyboardInterrupt
is another exception that you may not want to catch. (Using except Exception
will not catch either SystemExit
or KeyboardInterrupt
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With