Python Data Persistence 简明教程

Python Data Persistence - Marshal Module

Python 标准库中 marshal 模块的对象序列化特性类似于 pickle 模块。然而,此模块不用于一般用途的数据。另一方面,Python 本身使用它用于 Python 的内部对象序列化,以支持对 Python 模块(.pyc 文件)的编译版本进行读/写操作。

Object serialization features of marshal module in Python’s standard library are similar to pickle module. However, this module is not used for general purpose data. On the other hand, it is used by Python itself for Python’s internal object serialization to support read/write operations on compiled versions of Python modules (.pyc files).

marshal 模块使用的数据格式在 Python 版本之间不兼容。因此,一个版本的已编译 Python 脚本(.pyc 文件)很可能会在另一个版本上执行。

The data format used by marshal module is not compatible across Python versions. Therefore, a compiled Python script (.pyc file) of one version most probably won’t execute on another.

就像 pickle 模块一样,marshal 模块还定义了 load() 和 dump() 函数,用于从/到文件中读取和写入编组对象。

Just as pickle module, marshal module also defined load() and dump() functions for reading and writing marshalled objects from / to file.

dump()

此函数将受支持 Python 对象的字节表示形式写入文件。该文件本身是一个具有写权限的二进制文件。

This function writes byte representation of supported Python object to a file. The file itself be a binary file with write permission

load()

此函数从二进制文件读取字节数据并将其转换为 Python 对象。

This function reads the byte data from a binary file and converts it to Python object.

以下示例演示了使用 dump() 和 load() 函数来处理 Python 的代码对象,这些代码对象用于存储预编译的 Python 模块。

Following example demonstrates use of dump() and load() functions to handle code objects of Python, which are used to store precompiled Python modules.

此代码使用内置的 compile() 函数根据嵌入 Python 指令的源字符串构建代码对象。

The code uses built-in compile() function to build a code object out of a source string which embeds Python instructions.

compile(source, file, mode)

file 参数应该是从中读取代码的文件。如果没有从文件读取,则传递任意字符串。

The file parameter should be the file from which the code was read. If it wasn’t read from a file pass any arbitrary string.

如果源包含语句序列,则 mode 参数为 'exec',如果有一个表达式,则为 'eval',如果包含一个交互式语句,则为 'single'。

The mode parameter is ‘exec’ if the source contains sequence of statements, ‘eval’ if there is a single expression or ‘single’ if it contains a single interactive statement.

然后使用 dump() 函数将编译代码对象存储在 .pyc 文件中。

The compile code object is then stored in a .pyc file using dump() function.

import marshal
script = """
a=10
b=20
print ('addition=',a+b)
"""
code = compile(script, "script", "exec")
f=open("a.pyc","wb")
marshal.dump(code, f)
f.close()

要反序列化,使用 load() 函数从 .pyc 文件中获取对象。由于它返回一个代码对象,因此可以使用 exec()(另一个内置函数)运行它。

To deserialize, the object from .pyc file use load() function. Since, it returns a code object, it can be run using exec(), another built-in function.

import marshal
f=open("a.pyc","rb")
data=marshal.load(f)
exec (data)