Aman Gupta
Aman Gupta

Reputation: 43

Re-running a python script from where it was stopped

I am preparing a python script which contains 4 functions, and a main function calling them. When the script is ran, all the functions are executed one by one, but I manually terminated the script after 2nd function is executed completely.

Now I want, when the script is re-run, it should ignore first two function and start with the 3rd one.

I got one idea to use a file and add an entry for each function when it is executed and next time read from that file, but it will require too much of nested if.

Any other ideas?

Upvotes: 4

Views: 104

Answers (3)

rassar
rassar

Reputation: 5660

Put the function calls in a try/catch with Keyboard interrupt

fn = 0 # read from file
try:
    if fn < 1: f1()
    fn=1
    if fn < 2: f2()
    fn=2
    ...
except KeyboardInterrupt: # user stopped
    ... # write fn to file

This cuts down on code repetition from writing fn to a file.

If you know what order you want the functions to run in you could do this:

fn = 0 # read from file
fn_reached = fn
functions = [f1, f2, f3, f4] # list of function objects
try:
     for f in functions[fn:]:
         f()
         fn_reached += 1
except KeyboardInterrupt:
     ... # write fn_reached to file

If you want the program to reset after a full run, try this:

if fn_reached == len(functions):
    ... # write 0 to file

Upvotes: 1

Gaurav
Gaurav

Reputation: 543

Other solution being using an environment variable, You can define a utility function, that will call all function. which will check if the environment variable is set.

import os
def utiltiy_function():
    function_count = os.environ.get("function_count")
    if not function_count:
        os.environ['function_count']=0 #this will set initially value when the function has not been called
    if function_count==0:
         func_1()
    elif function_count==1:
         func_2()
    elif function_count==2:
         func_3()
    elif function_count==3:
         func_4()
    else:
         pass

and in each function end you can update the value of the environment variable, If you still have doubt let me know.

Upvotes: 1

Nadav Har&#39;El
Nadav Har&#39;El

Reputation: 13731

Why "nested" ifs? If the functions are supposed to run in sequence, you can write the number of the last function to finish to a file, and then have a sequence of non-nested ifs, e.g, something like this pseudo-code

... # read n from file, or 0 if it doesn't exist
if n < 1:
    f1()
    ... # write 1 to the file
if n < 2:
    f2()
    ... # write 2 to the file
if n < 3:
    f3()
    ... # write 3 to the file
...

So indeed one if per function, but no nesting.

If the functions may run in a different order, you can write a different file for each one, or a different line into a single file as you suggested, but I don't understand why it will have to be nested ifs.

Upvotes: 3

Related Questions