Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 991
jrdioko Avatar asked Apr 19 '10 18:04

jrdioko


People also ask

How do I use except KeyboardInterrupt in python?

In Python, there is no special syntax for the KeyboardInterrupt exception; it is handled in the usual try and except block. The code that potentially causes the problem is written inside the try block, and the 'raise' keyword is used to raise the exception, or the python interpreter raises it automatically.

Does exception catch KeyboardInterrupt?

KeyboardInterrupt exception inherits the BaseException and similar to the general exceptions in python, it is handled by try except statement in order to stop abrupt exiting of program by interpreter. As seen above, KeyboardInterrupt exception is a normal exception which is thrown to handle the keyboard related issues.

What is KeyboardInterrupt error in python?

Keyboard Interrupt Error The KeyboardInterrupt exception is raised when you try to stop a running program by pressing ctrl+c or ctrl+z in a command line or interrupting the kernel in Jupyter Notebook.


1 Answers

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.

like image 187
jrdioko Avatar answered Oct 10 '22 01:10

jrdioko