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.
There are a few ways that one can exit when
SystemExitis 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.