Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

python - 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 project1MODULEsubmodulemain.py. The window module is project1MODULEwindow.py. main.py begins:

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

The module I'm attempting to load from is in project2project2subMODULEdata.py, with no messing with the sys path.

MODULE is the same in both cases: the module I want to load is project2project2subMODULEwindow.py.

Could the sys.path appending mess this up somehow?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...