Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I exit() a script but it does NOT exit

Tags:

python

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?

like image 284
Ricard Bou Avatar asked Nov 28 '22 08:11

Ricard Bou


2 Answers

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.

like image 61
Pavel Anossov Avatar answered Dec 06 '22 11:12

Pavel Anossov


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.)

like image 26
Edward Loper Avatar answered Dec 06 '22 11:12

Edward Loper