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

我正在尝试将 Python 2 代码转换为 Python 3。我pickle.loads在 Python 2.7 中使用了该函数,根据其文档,该函数执行以下操作(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)。我想obj在 Python 3 中检索。当我这样做时pickle.loads(x),我收到以下错误:


a bytes-like object is required, not 'str'

改为pickle.loads(x)改为pickle.loads(bytes(x, 'utf-8'))会出现以下错误:


invalid load key, '\x5c'.

如何obj从xPython 3 中获取?


千巷猫影
浏览 186回答 1
1回答

当年话下

更改pickle.loads(x)为pickle.loads(bytes(x, 'latin-1'))。更改pickle.dumps(o)为str(pickle.dumps(o, protocol=0), 'latin-1')。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python