Yuval Eliav
Yuval Eliav

Reputation: 169

How to interrupt a python program?

I have made a program that essentially runs a loop like so:

while(true):
    i = 0
    while(i < 60):
        i += 1
        time.sleep(1)

I would like to be able to pause it while it is running and go back to it (keeping the i as it was when interrupted) . Currently the program has nothing to do with taking an input from the user and it just runs in the background. Is there a way to pause a running script in a way that will keep the code at the same state that it was when I paused it and be able to continue from that point? The program runs either on pycharm or normal Python 2.7 through the cmd.
(I have some basic knowledge of key logging and thread usage. So if that will work I am willing to try it out).

Upvotes: 6

Views: 5234

Answers (2)

Cody Braun
Cody Braun

Reputation: 657

You could catch a keyboard interrupt exception (how you'd normally end the program) and then wait until the user presses enter again. That'd be something like this

while(true):
    i = 0
    while(i < 60):
        try:
            i += 1
            time.sleep(1)
        except KeyboardInterrupt:
            input('Press enter to continue')

Upvotes: 3

kwarunek
kwarunek

Reputation: 12577

In *nix environment, simply press Ctrl+Z, process will be "paused" in background. To resume use commands: fg in foreground, bg in background. To see all jobs.

There is no action required in python to work this on linux.

Upvotes: 2

Related Questions