I exit () a script, but it does NOT exit

I am trying to exit the script, but it does not exit.

Here is my code:

import sys try: ... print "I'm gonna die!" sys.exit() except: ... print 'Still alive!' 

And the results:

 I'm gonna die! Still alive! 

Why?

+4
source share
3 answers

If you really need to exit immediately and want to skip normal exit processing, you can use os._exit(status) . But, as others have said, it is usually best to go out of the normal way and just not catch the SystemExit exception. And while we're in the subject, KeyboardInterrupt is another exception that you might not want to catch. (Using except Exception will not capture either SystemExit or KeyboardInterrupt .)

+1
source

You catch the SystemExit exception in your except blanket. Do not do this. Always indicate which exceptions you expect to avoid with just these things.

+22
source

sys.exit() is implemented by creating a SystemExit exception, so the cleanup actions specified at the end, with the exception of the try statements, are executed, and you can intercept an attempt to reach the external level.

In your SystemExit example, the following except SystemExit displayed.

+1
source

All Articles