[英]How to convert pickle.loads from Python 2 to Python 3?
I am trying to convert a Python 2 code into Python 3. I used the pickle.loads
function in Python 2.7, which according to its documentation does the following ( https://docs.python.org/2.7/library/pickle.html ): 我正在尝试将Python 2代码转换为Python 3.我在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.
However its behavior changes in Python 3 ( https://docs.python.org/3/library/pickle.html ): 但是它在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.
In the database, I have a string x
which was the output of pickle.dumps(obj)
performed in Python 2. I want to retrieve obj
in Python 3. When I do pickle.loads(x)
, I receive the following error: 在数据库中,我有一个字符串
x
,它是在Python 2中执行的pickle.dumps(obj)
的输出。我想在Python 3中检索obj
。当我执行pickle.loads(x)
,我收到以下错误:
a bytes-like object is required, not 'str'
Changing pickle.loads(x)
into pickle.loads(bytes(x, 'utf-8'))
instead gives the following error: 将
pickle.loads(x)
更改为pickle.loads(bytes(x, 'utf-8'))
而不是出现以下错误:
invalid load key, '\x5c'.
How can I obtain obj
from x
in Python 3? 如何在Python 3中从
x
获取obj
?
Change pickle.loads(x)
to pickle.loads(bytes(x, 'latin-1'))
. 将
pickle.loads(x)
更改为pickle.loads(bytes(x, 'latin-1'))
。
Change pickle.dumps(o)
to str(pickle.dumps(o, protocol=0), 'latin-1')
. 将
pickle.dumps(o)
更改为str(pickle.dumps(o, protocol=0), 'latin-1')
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.