Is there a way to save the state of a class??
Alex Martelli
aleaxit at yahoo.com
Fri Apr 20 17:36:35 EDT 2001
"EdwardT" <edwardt at trillium.com> wrote in message
news:9bpra9$q0l at news.or.intel.com...
> Hello, I current have a script that do certain processing on files, and
> requires user to enter certain info such as:
> 1. inputfile name
> 2. output file name
> 3. whether it would like process all files recusively or just one (stored
as
> a Int instance in class, value got from CheckButton widget in runtime )
> 4. a string that supplies the protocol stack it is building. (stored as a
> string instance in class)
By "in class" I guess you mean, as an attribute in an instance
of some class?
>
> Instead of writing some code to save all these some sort of text file;
and
> re-read the next time ithe script got invoked. Does python offer the
option
> to save the state of the whole script, as some kind of persistence
objects?
"The state of the whole script" would be more of a problem -- isn't it
enough to save the state of an instance, as you ask before and in the
subject (assuming that's what you mean by 'state of a class')?
Standard module pickle does that (and cPickle does it, too, but
faster). Here's a simple example -- assume the following is
scriptfile flup.py:
import sys, cPickle
class Words:
def __init__(self, *words):
self.words = words
if len(sys.argv)>1:
# build and persist an object
obj = Words(*sys.argv[1:])
cPickle.dump(obj, open("flup.dat","wb"))
else:
# depersist and display an object
obj = cPickle.load(open("flup.dat","rb"))
for word in obj.words:
print word,
print
An example usage might be:
D:\ian>python flup.py be bop blippo
D:\ian>python flup.py
be bop blippo
D:\ian>
Lots more info, and examples of more advanced usage, are in
the standard Python library reference manual.
Alex
More information about the Python-list
mailing list