【问题标题】:Unpickle already pickled file解压已经腌制的文件
【发布时间】:2021-03-05 03:39:44
【问题描述】:
我已经腌制了文件,我用它来取消腌制它
with open(meta_path, 'rb') as f:
result = pickle.load(f)
在我的机器上python3版本是3.6.9
python2版本为2.7.17
大多数答案都假设在转储期间使用 protocol=2 作为
this answer
但问题是文件已经被转储了我没有腌制它,这就是为什么我不知道使用了哪个协议。
谁能帮我取消腌制这个文件?
【问题讨论】:
标签:
python-3.x
python-2.7
pickle
python-2to3
【解决方案1】:
您可以使用pickletools 来识别协议版本。查看使用了哪个版本的标准输出。可能 Python2 无法使用 > 2 的协议版本来取消转储。
import pickle
import pickletools
obj = {'load': pickle.load}
# dump all Python3 supported versions
for x in range(0, 6):
filename = '/tmp/data_v{x}.pickle'
with open(filename, 'wb') as f:
pickle.dump(obj, f, protocol=x)
with open(filename, 'rb') as f:
print(pickletools.dis(f))
退出 Python3(截断):
highest protocol among opcodes = 0
0: } EMPTY_DICT
1: q BINPUT 0
3: X BINUNICODE 'load'
12: q BINPUT 1
14: c GLOBAL 'pickle load'
27: q BINPUT 2
29: s SETITEM
30: . STOP
highest protocol among opcodes = 1
0: \x80 PROTO 2
2: } EMPTY_DICT
3: q BINPUT 0
5: X BINUNICODE 'load'
14: q BINPUT 1
16: c GLOBAL 'pickle load'
29: q BINPUT 2
31: s SETITEM
32: . STOP
highest protocol among opcodes = 2
0: \x80 PROTO 3
...