序列化Python代码对象(来自compile())
通过创建 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>
我想将该对象存储在字符串或文件中,以便稍后可以再次从文件构造 obj。 (我不想存储纯字符串。)
After creating a Python code object via
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>
I would like to store that object in a string or file such that I can later construct the obj from the file again. (I do not want to store the plain string.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我也遇到过同样的任务。
您可以使用
marshal
,其中包含常见的警告和 文档:存储到文件:
另存为字符串:
I've come across the same task.
You can use
marshal
, with the usual warning and some other limitations listed in the docs:Storing to file:
Saving as string: