鉴于 python 中的泡菜转储,我如何确定使用的协议? [英] Given a pickle dump in python how to I determine the used protocol?
问题描述
假设我有一个泡菜转储——无论是作为一个文件还是一个字符串——我如何确定用于自动创建泡菜转储的协议?
Assume that I have a pickle dump - either as a file or just as a string - how can I determine the protocol that was used to create the pickle dump automatically?
如果是这样,我是否需要阅读整个转储来找出协议,还是可以在 O(1) 中实现?通过 O(1),我考虑了 pickle 字符串或文件开头的一些标头信息,其读出不需要处理整个转储.
And if so, do I need to read the entire dump to figure out the protocol or can this be achieved in O(1)? By O(1) I think about some header information at the beginning of the pickle string or file whose read out does not require processing the whole dump.
非常感谢!
我对此有更新,显然下面给出的答案在python 3.4下并不总是有效.如果我只是用协议 1 腌制值 True
,有时我只能恢复协议 0 :-/
I have an update on this, apparently the answer given below does not always work under python 3.4. If I simply pickle the value True
with protocol 1, sometimes I can only recover protocol 0 :-/
推荐答案
您可以使用 picketools
推出自己的方案:
You could roll your own using picketools
:
with open('your_pickle_file', 'rb') as fin:
op, fst, snd = next(pickletools.genops(fin))
proto = op.proto
PROTO 标记似乎只写为协议为 2 或更大的第一个元素.否则,第一个元素是一个标记或元素,指示协议是 0 还是 1.
It appears that a PROTO marker is only written as the first element where the protocol is 2 or greater. Otherwise, the first element is a marker or element that indicates if the protocol is 0 or 1.
更新以征集更多土地:
pops = pickletools.genops(pickle_source)
proto = 2 if next(pops)[0].proto == 2 else int(any(op.proto for op, fst, snd in pops))
这篇关于鉴于 python 中的泡菜转储,我如何确定使用的协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!