Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, can I prevent a function from catching KeyboardInterrupt and SystemExit?

I am writing some code in Python something like this:

import sys
try:
    for x in large_list:
        function_that_catches_KeyboardInterrupt(x)
except KeyboardInterrupt:
    print "Canceled!"
    sys.exit(1)

When I try to interrupt the loop, I basically need to hold down Control+C long enough to cancel every invocation of the function for all the elements of large-list, and only then does my program exit.

Is there any way I can prevent the function from catching KeyboardInterrupt so that I can catch it myself? The only way I can think of would be to abuse threading by creating a separate thread just for calling the function, but that seems excessive.

Edit: I checked the offending code (which I can't easily change), and it actually uses a bare except:, so even sys.exit(1) is caught as a SystemExit exception. How can I escape from the bare except: block and quit my program?

like image 994
Ryan C. Thompson Avatar asked Jan 26 '12 20:01

Ryan C. Thompson


1 Answers

You can rebind the SIGINT handler using the signal library.

import signal, sys
def handler(signal, frame):
    print "Canceled!"
    sys.exit(1)
signal.signal(signal.SIGINT, handler)
for x in large_list:
    function_that_catches_KeyboardInterrupt(x)

There are a few ways that one can exit when SystemExit is being caught. os._exit(1) will do a c-style exit with no cleanup. os.kill(os.getpid(), signal.SIGTERM) will allow the interpreter some level of cleanup, I believe flushing/closing file handles, etc.

like image 64
stefan Avatar answered Sep 28 '22 02:09

stefan