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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With