Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving program state when user invokes Ctrl-C

Tags:

python

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?

like image 387
ARF Avatar asked Dec 24 '22 06:12

ARF


2 Answers

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

like image 144
Cassum Avatar answered Dec 26 '22 18:12

Cassum


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
like image 45
chthonicdaemon Avatar answered Dec 26 '22 18:12

chthonicdaemon