问题描述
我正在尝试释放在python3中腌制的对象.这适用于python3,但不适用于python2.该问题可以重现为pickle协议0.示例代码:
I'm trying to unpickle objects pickled in python3. This works in python3 but not in python2. The issue can be reproduced down to pickle protocol 0. Example code:
import pickle
import collections
o = collections.OrderedDict([(1,1),(2,2),(3,3),(4,4)])
f = open("test.pkl", "wb")
pickle.dump(o, f, 0)
f.close()
这将导致以下pkl文件:
This results in the following pkl file:
python2:
ccollections
OrderedDict
p0
((lp1
(lp2
I1
aI1
aa(lp3
I2
aI2
aa(lp4
I3
aI3
aa(lp5
I4
aI4
aatp6
Rp7
python3:
cUserString
OrderedDict
p0
(tRp1
L1L
L1L
sL2L
L2L
sL3L
L3L
sL4L
L4L
s.
当我尝试从python2加载在python3中创建的pickle文件时,出现以下异常:
When I try to load the pickle file created in python3 from python2 I'm getting the following exception:
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> f = open("test.pkl", "rb")
>>> p = pickle.load(f)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/pickle.py", line 1378, in load
return Unpickler(file).load()
File "/usr/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
File "/usr/lib/python2.7/pickle.py", line 1090, in load_global
klass = self.find_class(module, name)
File "/usr/lib/python2.7/pickle.py", line 1126, in find_class
klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'OrderedDict
但是,将泡菜文件中的第一行从UserString更改为collections即可解决此问题.
However changing first line in the pickle file from UserString to collections sort of solves the problem.
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> f = open("test.pkl", "rb")
>>> p = pickle.load(f)
>>> p
OrderedDict([(1L, 1L), (2L, 2L), (3L, 3L), (4L, 4L)])
这是python3中的pickle中的错误吗?
Is this a bug in pickle in python3?
推荐答案
确保在Python 2中导入collections
.此代码对我有用:
Make sure you import collections
in Python 2. This code works for me:
Python 3-进行腌制:
Python 3 - do the pickling:
import pickle
import collections
o = collections.OrderedDict([(1,1),(2,2),(3,3),(4,4)])
with open('/home/bo/Desktop/test.pkl', 'wb') as f:
pickle.dump(o, f, 2)
Python 2-进行解腌:
Python 2 - do the unpickling:
import pickle
import collections
with open('/home/bo/Desktop/test.pkl', 'rb') as f:
o = pickle.load(f)
当我这样做时,我可以毫无问题地阅读o
:
When I do that I can read o
with no issue:
>>> o
0: OrderedDict([(1, 1), (2, 2), (3, 3), (4, 4)])
这篇关于从python2中的python3解开OrderedDict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!