gpt4 book ai didi

python - 在 python2 中从 python3 解开 OrderedDict

转载 作者:太空宇宙 更新时间:2023-11-04 05:42:04 27 4
gpt4 key购买 nike

我正在尝试取消在 python3 中 pickle 的对象。这在 python3 中有效,但在 python2 中无效。该问题可以重现到 pickle 协议(protocol) 0。示例代码:

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 文件:

python 2:

ccollections
OrderedDict
p0
((lp1
(lp2
I1
aI1
aa(lp3
I2
aI2
aa(lp4
I3
aI3
aa(lp5
I4
aI4
aatp6
Rp7

python 3:

cUserString
OrderedDict
p0
(tRp1
L1L
L1L
sL2L
L2L
sL3L
L3L
sL4L
L4L
s.

当我尝试从 python2 加载在 python3 中创建的 pickle 文件时,出现以下异常:

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

然而,将 pickle 文件中的第一行从 UserString 更改为集合可以解决问题。

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 的错误吗?

最佳答案

确保在 Python 2 中导入 collections。这段代码对我有用:

Python 3 - 进行 pickle :

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 - 执行 unpickling:

import pickle
import collections

with open('/home/bo/Desktop/test.pkl', 'rb') as f:
o = pickle.load(f)

当我这样做时,我可以毫无问题地阅读 o:

>>> o
0: OrderedDict([(1, 1), (2, 2), (3, 3), (4, 4)])

关于python - 在 python2 中从 python3 解开 OrderedDict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33568844/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com