Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a Python program get into a function and finish with Ctrl+X while running?

Tags:

python

My Python program takes a lot of time to complete all the iterations of a for loop. The moment I hit a particular key/key combination on the keyboard while it is running, I want it to go into another method and save the variables into the disk (using pickle which I know) and exit the program safely.

Any idea how I can do this?

Is the KeyboardInterrupt a safe way to this just be wrapping the for loop inside the KeyboardInterrupt exception, catching it and then saving the variables in the except block?

like image 610
London guy Avatar asked Nov 10 '22 02:11

London guy


1 Answers

It is only safe if, at every point in your loop, your variables are in a state which allows you to save them and resume later.

To be safe, you could instead catch the KeyboardInterrupt before it happens and set a flag for which you can test. To make this happen, you need to intercept the signal which causes the KeyboardInterrupt, which is SIGINT. In your signal handler, you can then set a flag which you test for 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 have control over the point at which the function is interrupted. You can add checks for if interrupted at any place you like. This helps with being in a consistent, resumable state when the function is being interrupted.

(With python3, this could be solved nicer using nonlocal; this is left as an excercise for the reader as the Asker did not specify which Python version they are at.)

(This should work on Windows according to the documentation, but I have not tested it. Please report back if it does not so that future readers are warned.)

like image 55
Jonas Schäfer Avatar answered Nov 14 '22 23:11

Jonas Schäfer