Saving the state of the program when the user invokes Ctrl-C

In python, when the user calls Ctrl-C, what happens? Do I have the opportunity to save the state of the program?

What about context managers? Is the section running __exit__()?

+4
source share
3 answers

Basically, an exception KeyboardInterruptis thrown inside the main thread. So yes, you can handle it by catching it in try / except block and the __exit__()sections are executed

https://docs.python.org/2/library/exceptions.html#exceptions.KeyboardInterrupt

+5
source

atexit. . , , :

import atexit

@atexit.register
def exithandler():
    print("Exit trapped!")

if __name__ == '__main__':
    while True:
        pass
+3

I just mentioned signal , which is also built-in, which can handle Ctrl+ Cand many more signals, for example SIGHUP, etc.

import signal

def signal_handler(signal, frame):
    # Do work
    # Thread cleanup
    # pickle program state
    # remove(pidfile) # as an example
    exit(0)

signal.signal(signal.SIGINT, signal_handler)

This is just an example of a wide structure that can handle multiple signals.
Here is a list of some signals you could catch.

0
source

All Articles