I'm trying to use the shelve python module to save my session output and reload it later, but I have found that if I have defined functions then I get an error in the reloading stage. Is there a problem with the way I am doing it? I based my code on an answer at How can I save all the variables in the current python session? .
Here's some simple code that reproduces the error:
def test_fn(): #simple test function
return
import shelve
my_shelf = shelve.open('test_shelve','n')
for key in globals().keys():
try:
my_shelf[key] = globals()[key]
except: #__builtins__, my_shelf, and imported modules cannot be shelved.
pass
my_shelf.close()
Then if I exit I can do
ls -lh test_shelve*
-rw-r--r-- 1 user group 22K Aug 24 11:16 test_shelve.bak
-rw-r--r-- 1 user group 476K Aug 24 11:16 test_shelve.dat
-rw-r--r-- 1 user group 22K Aug 24 11:16 test_shelve.dir
In general, in a new IPython session I want to be able to do something like:
import shelve
my_shelf = shelve.open('test_shelve')
for key in my_shelf:
globals()[key]=my_shelf[key]
This produces an error for key 'test_fn'. Here is some code to demonstrate the error:
print my_shelf['test_fn']
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-4-deb481380237> in <module>()
----> 1 print my_shelf['test_fn']
/home/user/anaconda2/envs/main/lib/python2.7/shelve.pyc in __getitem__(self, key)
120 except KeyError:
121 f = StringIO(self.dict[key])
--> 122 value = Unpickler(f).load()
123 if self.writeback:
124 self.cache[key] = value
AttributeError: 'module' object has no attribute 'test_fn'
Of course, one solution would be to exclude functions in the saving stage, but from what I have read it should be possible to restore them with this method, and so I wondered if I am doing things wrongly.