When I restart the script I want it to pick up where it left off

So I use the following code to prevent my code from running too long. When the time runs out, the script exits, and when I restart the script, I want it to pick up where it left off. How do I do that? This is just for challenge and curiosity.

import signal 


def handler(signum, frame): 
    print("Time's up!") 
    raise SystemExit(1) 


signal.signal(signal.SIGALRM, handler) 
signal.alarm(10) 

# My code here 

signal.alarm(0) # Cancel the alarm

The basic approach is to store the pogramme state in a file (or a
database record etc, anything which persists beyond the run time of the
programme).

How complex that is depends on your programme. If you’re processing
lines of data, maybe you just need to regularly save the line number or
file offset, and read that on programme start.

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like

How about using the pickle (pickle — Python object serialization — Python 3.11.4 documentation) or json (json — JSON encoder and decoder — Python 3.11.4 documentation) libraries?

How about using the pickle
(pickle — Python object serialization — Python 3.12.1 documentation)

Personally, I don’t really use pickle because it’s Python specific -
nonPython things can’t read it.

That said, to save Python state it might be very suitable. Note that it
will save all the state of the variables you decide to save, so
complex object trees etc get saved complete.

If you’re processing something simple, saving just a “how far” number
might be simpler.

or json (json — JSON encoder and decoder — Python 3.12.1 documentation) libraries?

This would be one my shortlist. It is simple and readable by other
(nonPython) things, such as the human eye.

You do need to decide what you need to keep, but you need to decide that
anyway. I would go for simple.

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like