Resuming a program's execution after correcting error

MRAB google at mrabarnett.plus.com
Tue Oct 3 19:58:17 EDT 2006


Sheldon wrote:
> MRAB wrote:
> > Sheldon wrote:
> > > Hi.
> > >
> > > Does anyone know if one can resume a python script at the error point
> > > after the error is corrected?
> > > I have a large program that take forever if I have to restart from
> > > scratch everytime. The error was the data writing a file so it seemed
> > > such a waste if all the data was lost and must be recalculated again.
> > >
> > You could modify the program while you're debugging it so that instead
> > of, say:
> >
> >     calculate data
> >     write data
> >
> > you have:
> >
> >     if saved data exists:
> >         load data
> >     else:
> >         calculate data
> >         save data
> >     write data
> >
> > The pickle module would be useful here.
> >
> > Matthew
>
> I like your idea Matthew but I don't know how to pickle the many
> variables in one file. Do I need to pickle each and every variable into
> a seperate file?
> var1,var2
> pickle.dump(var1,f)
> pickle.dump(var2,f2)
>
Using the 'pickle' module:

    # To store:
    f = open(file_path, "wb")
    pickle.dump(var1, f)
    pickle.dump(var2, f)
    f.close()

    # To load
    f = open(file_path, "rb")
    var1 = pickle.load(f)
    var2 = pickle.load(f)
    f.close()

A more flexible alternative is to use the 'shelve' module. This behaves
like a dict:

    # To store
    s = shelve.open(file_path)
    s["var1"] = "first"
    s["var2"] = [2, 3]
    s.close()

    # To load
    s = shelve.open(file_path)
    print s["var1"] # This prints "first"
    print s["var2"] # This prints [2, 3]
    s.close()

Hope that helps
Matthew




More information about the Python-list mailing list