更新时间:2023-11-28 23:21:16
出于安全考虑,您可以使用 ast.literal_eval
而不是 eval
:
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:
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.
...
Any suggestions for a better solution?
Thanks!
For a safety concern you can use ast.literal_eval
instead of eval
:
>>> import ast
>>> pickle.loads(ast.literal_eval(string_of_bytes_obj))
{'b': 2222, 'a': 1111}