pickle can't import a module that exists?

2019-02-18 05:02发布

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?

2条回答
做个烂人
2楼-- · 2019-02-18 05:26

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.

查看更多
迷人小祖宗
3楼-- · 2019-02-18 05:28

Check to make sure that you're importing classes in the loading programing in the same manner as you are in the saving program.

Saving:

 import window
 myObj.window_obj = window.wObj

Loading

 import window
 myObj = cPickle.loads(data)

NOT:

Saving:

 from window import wObj
 myObj.window_obj = wObj

Loading:

 import window
 myObj = cPickle.loads(data)
查看更多
登录 后发表回答