Avoiding accidentally catching KeyboardInterrupt and SystemExit in Python 2.4
- by jrdioko
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.)