6

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).

NerdOnTour
  • 634
  • 4
  • 15
Yuval Eliav
  • 169
  • 3
  • 18

2 Answers2

3

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')
NerdOnTour
  • 634
  • 4
  • 15
Cody Braun
  • 659
  • 6
  • 17
  • Though that would not keep your place in the inner loop for resuming – Eric Renouf Dec 12 '15 at 20:06
  • Oh right, the try/except should probably be inside that loop – Cody Braun Dec 12 '15 at 20:07
  • a keyboard interrupt exception is ctr+z (eof)? because i would normally end the program by shutting down the pycharm debugger or the cmd window – Yuval Eliav Dec 12 '15 at 20:23
  • Okay... I tried this out and it doesn't work all the way. I can interrupt the program by using ctrl + c but when i get back pressing the enter button the window writes back to me "SyntaxError: unexpected EOF while parsing" plus , this does not work in the pycharm debugger for some reason – Yuval Eliav Dec 12 '15 at 20:43
  • problem solved! the input function is bad and raw_input works perfectly, thank you! – Yuval Eliav Dec 15 '15 at 07:39
2

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.

kwarunek
  • 12,141
  • 4
  • 43
  • 48