views:

132

answers:

1

In Python scripts, there are many cases where a keyboard interrupt (Ctrl-C) fails to kill the process because of a bare except clause somewhere in the code:

try:
    foo()
except:
    bar()

The standard solution in Python 2.5 or higher is to catch Exception rather than using bare except clauses:

try:
    foo()
except Exception:
    bar()

This works because, as of Python 2.5, KeyboardInterrupt and SystemExit inherit from BaseException, not Exception. However, some installations are still running Python 2.4. How can this problem be handled in versions prior to Python 2.5?

(I'm going to answer this question myself, but putting it here so people searching for it can find a solution.)

+6  A: 

According to the Python documentation, the right way to handle this in Python versions earlier than 2.5 is:

try:
    foo()
except (KeyboardInterrupt, SystemExit):
    raise
except:
    bar()

That's very wordy, but at least it's a solution.

jrdioko
You should probably make the second `except` also `except Exception:`, to avoid catching other exceptions that aren't supposed to be caught.
Thomas Wouters