pickle 无法导入存在的模块?
为什么会发生这种情况?
import window; print "LOADED"; data = cPickle.loads(data)
结果是:
LOADED
Traceback (most recent call last):
...
import window; print "LOADED"; data = cPickle.loads(data)
exceptions.ImportError: No module named window
如果我执行import window
,它可以很好地加载模块,但是当使用cPickle
加载时,它似乎不起作用。
对于一些可能相关的附加信息:
我保存文件的模块位于 project1\MODULE\submodule\main.py
中。 window
模块是 project1\MODULE\window.py
。 main.py
开始:
import sys
sys.path.append("..\\..")
sys.path.append("..")
...
import window
我尝试加载的模块位于 project2\project2sub\MODULE\data.py
中,不会与 sys< /代码> 路径。
MODULE
在两种情况下都是相同的:我要加载的模块是 project2\project2sub\MODULE\window.py
。
附加的 sys.path 是否会以某种方式搞乱这个?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Pickle 取决于模块路径。无论您如何加载模块,如果您不弄乱
sys.path
,pickle 加载和保存应该可以工作。但是,如果您在一处导入 module.foo,并且 sys.path.append('module'); import foo,您有两个不同的模块路径:在第一个实例中,模块路径是module.foo
,而在第二个实例中,它只是foo
。这些并不等同,这会阻止 pickle 正常工作。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 doimport module.foo
in one place, andsys.path.append('module'); import foo
, you have two different module paths: in the first instance the module path ismodule.foo
while in the second it is justfoo
. These are not equivalent and that'll prevent pickle from working properly.检查并确保您在加载程序中导入类的方式与在保存程序中的方式相同。
保存:
正在加载
不:
保存:
正在加载:
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:
Loading
NOT:
Saving:
Loading: