In python, when the user invokes Ctrl-C, what happens? Do I have the possibility to save the program state?
What about context-managers? Does the __exit__()
section get executed?
Basically, a KeyboardInterrupt
exception is raised inside the main thread. So yes, you can handle it by catching it in try/except block and __exit__()
sections are executed
https://docs.python.org/2/library/exceptions.html#exceptions.KeyboardInterrupt
This is what the atexit module is for. You can register multiple exit handlers. You can see it at work by running this program and observing that a message is displayed:
import atexit
@atexit.register
def exithandler():
print("Exit trapped!")
if __name__ == '__main__':
while True:
pass
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