Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pickle can't import a module that exists?

Why might this happen?

import window; print "LOADED"; data = cPickle.loads(data)

The result is:

LOADED
Traceback (most recent call last):
...
    import window; print "LOADED"; data = cPickle.loads(data)
exceptions.ImportError: No module named window

It loads the module fine if I do import window, but when loading with cPickle it doesn't seem to work.

For some additional info which is likely relevant:

The module I saved the file in is in project1\MODULE\submodule\main.py. The window module is project1\MODULE\window.py. main.py begins:

import sys
sys.path.append("..\\..")
sys.path.append("..")
...
import window

The module I'm attempting to load from is in project2\project2sub\MODULE\data.py, with no messing with the sys path.

MODULE is the same in both cases: the module I want to load is project2\project2sub\MODULE\window.py.

Could the sys.path appending mess this up somehow?

like image 342
Claudiu Avatar asked May 18 '11 20:05

Claudiu


People also ask

How do I import a pickle module?

First, import pickle to use it, then we define an example dictionary, which is a Python object. Next, we open a file (note that we open to write bytes in Python 3+), then we use pickle. dump() to put the dict into opened file, then close. Use pickle.

What module do you import if you want to pickle objects?

Python pickle module is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on disk.

What does import pickle mean in Python?

Pickle in Python is primarily used in serializing and deserializing a Python object structure. In other words, it's the process of converting a Python object into a byte stream to store it in a file/database, maintain program state across sessions, or transport data over the network.

How do I save a pickle in Python?

To save a pickle, use pickle. dump . A convention is to name pickle files *. pickle , but you can name it whatever you want.


1 Answers

Pickle depends upon the module path. No matter how you load modules, if you don't mess with sys.path, pickle loading and saving should work. However, if you do import module.foo in one place, and sys.path.append('module'); import foo, you have two different module paths: in the first instance the module path is module.foo while in the second it is just foo. These are not equivalent and that'll prevent pickle from working properly.

like image 88
Claudiu Avatar answered Sep 20 '22 21:09

Claudiu