Is it possible to save a running program and reload next time ?

Richard Tew richard.m.tew at gmail.com
Thu Sep 21 13:18:17 EDT 2006


fdu.xiaojf at gmail.com wrote:
> I have a program which will continue to run for several days. When it is
> running, I can't do anything except waiting because it takes over most
> of the CUP time.
>
> Is it possible that the program can save all running data to a file when
> I want it to stop, and can reload the data and continue to run from
> where it stops when the computer is free ?

Yes.  Stackless Python can allow you to pickle running code and
to save it to disk and load it and continue running it from where it
left off.  It won't of course work if there is external state because
this will not be there, or necessarily still be relevant when the code
resumes.  So as long as you know the limitations and they suit
your uses, it should be usable for this.

http://www.stackless.com

Here's an example:

import stackless
import cPickle
import time

def f():
    n = 0
    while True:
        n += 1
        stackless.schedule()

t = stackless.tasklet(f)()

while True:
    # Run the tasklet until it yields or dies.
    t.run()
    # Yield to the operating system.
    try:
        time.sleep(0.1)
    except KeyboardInterrupt:
        if not t.alive:
            print "Tasklet unexpectedly dead"
            break

        # Serialise the running tasklet.
        v = cPickle.dumps(t)
        # Kill the old version.
        t.kill()

        # y / enter = continue
        # anything else = exit
        # otherwise stalled
        s = raw_input("Continue? [y]:").lower()
        if s not in ("y", ""):
            break

        t = cPickle.loads(v)

Unfortunately KeyboardInterrupt or probably any other
exception as a way of interrupting the running code is
problematic as it will kill the running tasklet if it happens
there instead of during the sleep.

Hope this helps,
Richard.




More information about the Python-list mailing list