且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python3 unpickle 字节对象的字符串表示

更新时间:2023-11-28 23:21:16

出于安全考虑,您可以使用 ast.literal_eval 而不是 eval:

>>>进口AST>>>pickle.loads(ast.literal_eval(string_of_bytes_obj)){'b':2222,'a':1111}

Is there a good way to load a bytes object that is represented as a string, so it can be unpickled?

Basic Example

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.

Attempt at a Solution

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}