[英]unpickle OrderedDict from python3 in python2
我正在嘗試解開在 python3 中腌制的對象。 這適用於python3但不適用於python2。 該問題可以重現到 pickle 協議 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 文件:
蟒蛇2:
ccollections
OrderedDict
p0
((lp1
(lp2
I1
aI1
aa(lp3
I2
aI2
aa(lp4
I3
aI3
aa(lp5
I4
aI4
aatp6
Rp7
蟒蛇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 更改為 collections 可以解決問題。
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 - 進行酸洗:
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 - 進行解壓:
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)])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.