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.
except Exception would be enough as SystemExit doesn't inherit from that...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.)
sys.exit() is implemented by raising the SystemExit exception, so cleanup actions specified by finally, except clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.
In your example SystemExit is catched by the following except statement.