[英]Python3 unpickle a string representation of bytes object
Is there a good way to load a bytes object that is represented as a string, so it can be unpickled? 有没有一种好的方法来加载表示为字符串的字节对象,以便可以将其取消腌制?
Here is a dumb example: 这是一个愚蠢的例子:
import pickle
mydict = { 'a': 1111, 'b': 2222 }
string_of_bytes_obj = str(pickle.dumps(mydict)) # Deliberate string representation for this quick example.
unpickled_dict = pickle.loads(string_of_bytes_obj) # ERROR! Loads takes bytes-like object and not string.
One solution is of course to eval
the string: 一种解决方案当然是
eval
字符串:
unpickled_dict = pickle.loads(eval(string_of_bytes_obj))
But, seems wrong to eval
, especially when the strings might be coming over a network or from a file. 但是,
eval
似乎是错误的,尤其是当字符串可能是通过网络或来自文件时。
... ...
Any suggestions for a better solution? 有更好的解决方案的建议吗?
Thanks! 谢谢!
For a safety concern you can use ast.literal_eval
instead of eval
: 为了安全起见,您可以使用
ast.literal_eval
而不是eval
:
>>> import ast
>>> pickle.loads(ast.literal_eval(string_of_bytes_obj))
{'b': 2222, 'a': 1111}
Is there a reason you need to have it as a str? 您是否有理由将其作为str? If you're just writing it to file, you can 'wb' instead of 'w'.
如果只是将其写入文件,则可以使用“ wb”代替“ w”。 ( https://pythontips.com/2013/08/02/what-is-pickle-in-python/ )
( https://pythontips.com/2013/08/02/what-is-pickle-in-python/ )
import pickle
mydict = { 'a': 1111, 'b': 2222 }
dumped = pickle.dumps(mydict)
string_of_bytes_obj = str(dumped) # Deliberate string representation for this quick example.
unpickled_dict = pickle.loads(dumped)
You can use encoding="latin1"
as an argument to str
and then use bytes
to convert back: 您可以将
encoding="latin1"
用作str
的参数,然后使用bytes
进行转换:
import pickle
mydict = { 'a': 1111, 'b': 2222 }
string_of_bytes_obj = str(pickle.dumps(mydict), encoding="latin1")
unpickled_dict = pickle.loads(bytes(string_of_bytes_obj, "latin1"))
Output: 输出:
>>> print(unpickled_dict)
{'a': 1111, 'b': 2222}
First of all i wouldn't use pickles to serialize data. 首先,我不会使用泡菜来序列化数据。 instead use Json.
而是使用Json。
my solution with pickles 我用泡菜的解决方案
import pickle
mydict = { 'a': 1111, 'b': 2222 }
string_of_bytes_obj = pickle.dumps(mydict) # Deliberate string representation for this quick example.
print(string_of_bytes_obj)
unpickled_dict = pickle.loads(string_of_bytes_obj)
print(unpickled_dict)
BUT with json 但是带有json
import json
mydict = { 'a': 1111, 'b': 2222 }
string_of_bytes_obj = json.dumps(mydict)
print(string_of_bytes_obj)
unpickled_dict = json.loads(string_of_bytes_obj)
print(unpickled_dict)
I highly recommend you to use json to serialize your data 我强烈建议您使用json序列化数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.