序列化Python代码对象(来自compile())

发布于 2025-01-15 07:55:30 字数 336 浏览 2 评论 0原文

通过创建 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

后知后觉 2025-01-22 07:55:30

我也遇到过同样的任务。

您可以使用 marshal,其中包含常见的警告和 文档

警告 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)

I've come across the same task.

You can use marshal, with the usual warning and some other limitations listed in the docs:

Warning The marshal module is not intended to be secure against erroneous or maliciously constructed data. Never unmarshal data received from an untrusted or unauthenticated source.

Storing to file:

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)

Saving as string:

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文