Avoiding accidentally catching KeyboardInterrupt and SystemExit in Python 2.4
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:开发者_JAVA技巧
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.)
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.
精彩评论