如何将pickle.loads从Python 2转换为Python 3?

时间:2019-04-22 09:28:35

标签: python python-3.x python-2.7 pickle

我正在尝试将Python 2代码转换为Python3。我在Python 2.7中使用了pickle.loads函数,根据它的文档,它执行以下操作(https://docs.python.org/2.7/library/pickle.html):

pickle.loads(string)
Read a pickled object hierarchy from a string. Characters in the 
string past the pickled object’s representation are ignored.

但是它的行为在Python 3(https://docs.python.org/3/library/pickle.html)中发生了变化:

pickle.loads(bytes_object, *, fix_imports=True, encoding="ASCII", errors="strict")
Read a pickled object hierarchy from a bytes object and return the 
reconstituted object hierarchy specified therein.

在数据库中,我有一个字符串x,它是在Python 2中执行的pickle.dumps(obj)的输出。我想在Python 3中检索obj。当执行{{1 }},我收到以下错误:

pickle.loads(x)

a bytes-like object is required, not 'str' 更改为pickle.loads(x)会产生以下错误:

pickle.loads(bytes(x, 'utf-8'))

如何在Python 3中从invalid load key, '\x5c'. 获得obj

1 个答案:

答案 0 :(得分:0)

pickle.loads(x)更改为pickle.loads(bytes(x, 'latin-1'))

pickle.dumps(o)更改为str(pickle.dumps(o, protocol=0), 'latin-1')