Pickle problem while loading a class instance.

Peter Otten __peter__ at web.de
Sat Apr 10 00:20:10 CEST 2010


gerardob wrote:

> 
> I tried both things:
> 
> 1- moved all the code to C:/Python26/lib/site-packages
> 2- Modified the PYTHONPATH in the windows registry.
> 
> However, i stil have exactly the same error on the screen.
> 
> Any other suggestions?

Did you heed my advice and make sure that your script reads and writes the 
pickle file in binary mode?

> file = open("prueba.txt", 'w')

The above line can trigger the same error; change "w" to "wb":

>>> import pickle
>>> class A: pass
...
>>> s = pickle.dumps(A())
>>> pickle.loads(s)
<__main__.A instance at 0x7f31d088ed88>

Seems to work. Now let's simulate the effect of writing in text and reading 
in binary mode:

>>> pickle.loads(s.replace("\n", "\r\n"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/pickle.py", line 1374, in loads
    return Unpickler(file).load()
  File "/usr/lib/python2.6/pickle.py", line 858, in load
    dispatch[key](self)
  File "/usr/lib/python2.6/pickle.py", line 1069, in load_inst
    klass = self.find_class(module, name)
  File "/usr/lib/python2.6/pickle.py", line 1124, in find_class
    __import__(module)
ImportError: No module named __main__

Peter



More information about the Python-list mailing list