How to get a Python program to enter a function and end with Ctrl + X while running?

My Python program takes a long time to complete all iterations of the for loop. At that moment, when I press a specific combination of keys / keys on the keyboard during its operation, I want her to switch to another method and save the variables to disk (using pickle, which I know) and safely exit the program.

Any idea how I can do this?

Is KeyboardInterrupt a safe way to do this simply by wrapping the for loop inside the KeyboardInterrupt exception, catching it, and then storing the variables in the exception block?

+5
source share
1 answer

This is safe if at every point in your cycle your variables are in a state that allows you to save them and resume them later.

To be safe, you could instead catch KeyboardInterrupt before this happens and set a flag for which you can test. For this to happen, you need to intercept the signal that causes KeyboardInterrupt , which is equal to SIGINT . In the signal handler, you can set a flag that you check in your calculation function. Example:

 import signal import time interrupted = False def on_interrupt(signum, stack): global interrupted interrupted = True def long_running_function(): signal.signal(signal.SIGINT, on_interrupt) while not interrupted: time.sleep(1) # do your work here signal.signal(signal.SIGINT, signal.SIG_DFL) long_running_function() 

The key advantage is that you control the point at which the function is interrupted. You can add checks for if interrupted anywhere you like. This helps in a constant, renewable state when the function is interrupted.

(With python3, this could be better used with nonlocal ; this is left as an exercise for the reader, since Asker did not indicate which version of Python they are on.)

(This should work on Windows in accordance with the documentation, but I have not tested it. Please report it if it is not, that future readers will be warned.)

+1
source

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


All Articles