In Python, can I prevent the KeyboardInterrupt and SystemExit distraction functions?

I write code in Python 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 abort the loop, I basically need to hold Control + C long enough to cancel all function calls for all large-list items, and only then will my program exit.

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

Edit: I checked the violation code (which I cannot easily change), and in fact it uses bare except: so even sys.exit(1) is called as a SystemExit exception. How can I escape from the bare except: block and exit my program?

+6
source share
1 answer

You can rebuild 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 several ways to exit when SystemExit caught. os._exit(1) will do the c-style exit without clearing. os.kill(os.getpid(), signal.SIGTERM) will allow the interpreter to get some level of cleanup, I believe that files clean / close files, etc.

+6
source

Source: https://habr.com/ru/post/906981/


All Articles