In A Pickle Over Pickle()

n89553 at stud.upb.de n89553 at stud.upb.de
Sat Jan 22 07:33:45 EST 2000


wolf at one.net wrote:
> 
> I'm using Python to create a text-adventure writing system, and need
> to use pickle to save/restore the program state. The problem is, I
> seem to have a mental block when it comes to Pickle--I've read all the
> documentation I can find on pickle() and can't make heads or tails of
> it. I suspect I'm missing some obvious "first clue" that would make it
> come together.
Perhaps it´s just too easy.

>>> menu = ["spam", "fries", "spam", "tatties", "lobster", "spam" , "fries" , "vanille fla", "spam" , "spam"] 
>>> import pickle
>>> jar = pickle.Pickler(open("spamfile", "w"))
>>> jar.dump(menu)
>>> del jar, menu
>>> print open("spamfile").read()
(lp0
S'spam'
p1
aS'fries'
p2
ag1
aS'tatties'
p3
aS'lobster'
p4
ag1
ag2
aS'vanille fla'
p5
ag1
ag1
a.
>>> jar = pickle.Unpickler(open("spamfile", "r"))
>>> print jar.load()
['spam', 'fries', 'spam', 'tatties', 'lobster', 'spam', 'fries',
'vanille fla', 'spam', 'spam']


> "skeleton" that has no variables of its own. Basically what I want to
> do is pickle/unpickle the *entire* mess, variables, dictionaries, etc,

What about something like:
>>> jar = pickle.dump((vars(), vars(my_module_NewZorkCity.topten)),  open("spamfile", "w"))

There´s another module, called shelve.py .
Shelves almost look like dictionaries, but they store their data on
disk.
>>> import shelve
>>> users=("NewZorkCity-users") # this shelve looks like a dictionary
>>> users["green_knight"]= userdata,NewZorkCity.state()
>>> users[""]=userdata, NewZorkCity.state()
>>> for user in users.keys():
...     print user
...
green_knight
spanish_inquisitor
>>> selected_userdata, selected_state = users["green_knight"]

shelve.py tries to guess which dbm to use. Python 1.5.2 can´t recognize
the magic cookies of some versions of bsddb , but there´s a patch
for whichdb.py at www.python.org

regards,

Mirko
-- 
M Liß, <n89553 at squid.upb.de>



More information about the Python-list mailing list