The Dare Guy
The Dare Guy

Reputation: 496

I exit() a script but it does NOT exit

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?

Upvotes: 4

Views: 459

Answers (3)

Edward Loper
Edward Loper

Reputation: 15944

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

Upvotes: 1

Maksym Polshcha
Maksym Polshcha

Reputation: 18358

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.

Upvotes: 1

Pavel Anossov
Pavel Anossov

Reputation: 62868

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.

Upvotes: 23

Related Questions