通过创建Python代码对象后
code = """a = 5
a += 6
print(a)
"""
obj = compile(code, "foobar.py", "exec")
print(obj)
<code object <module> at 0x7f6bef0ea190, file "foobar.py", line 1>
我想将该对象存储在字符串或文件中,以便稍后可以再次从文件构造该对象。 (我不想存储纯字符串。)
我也遇到过同样的任务。
您可以使用
marshal
,以及 docs 中列出的常见警告和一些其他限制:
警告 marshal 模块并非旨在防止错误或恶意构建的数据。切勿解组从不受信任或未经身份验证的来源收到的数据。
存储到文件:
import marshal
with open("foobar.pyc", "wb") as f:
marshal.dump(obj, f)
with open("foobar.pyc", "rb") as f:
obj_restored = marshal.load(f)
print(obj_restored == obj)
另存为字符串:
import base64
import marshal
serialized = marshal.dumps(obj)
obj_bytes = base64.b64encode(serialized) # b64 bytes
obj_ascii_str = obj_bytes.decode("ascii") # b64 string for json
restored_serialized = base64.b64decode(obj_ascii_str)
obj_restored = marshal.loads(restored_serialized)
print(obj_restored == obj)