简体   繁体   中英

Saving program state when user invokes Ctrl-C

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

I'll just mention signal which is also a built in that can handle Ctrl + C and many more signals such as 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 a example of a broad framework that can handle numerous signals.
Here's a list of some of the signals you could catch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM