posts - 431,  comments - 344,  trackbacks - 0
marshal模块使用了简单的自描述格式(Self-Describing Formats)把不连续的数据组合起来与字符串相互转化, 这样它们就可以写入文件或者是在网络中传输, 对于每个数据项目, 格式化后的字符串都包含一种类型代码, 然后是一个或者多个类型标识区域. 整数使用小字节序(little-endian order)储存, 字符串储存时和它自身内容长度相同(可能包含空字节), 元组由组成它的对象组合表示. 它支持大多数的内建数据类型, 包括code对象. Python自身也使用了这个格式来存储编译后代码(.pyc文件).
使用 marshal 模块组合不连续数据:
import marshal
value = (
"this is a string",
[1, 2, 3, 4],
("more tuples", 1.0, 2.3, 4.5),
"this is yet another string"
)
data = marshal.dumps(value)
# intermediate format
print type(data), len(data)
print "-"*50
print repr(data)
print "-"*50
print marshal.loads(data)

输出结果为:
<type 'str'> 130
--------------------------------------------------
'(\x04\x00\x00\x00s\x10\x00\x00\x00this is a string[\x04\x00\x00\x00i\x01\x00\x00\x00i\x02\x00\x00\x00i\x03\x00\x00\x00i\x04\x00\x00\x00(\x04\x00\x00\x00s\x0b\x00\x00\x00more tuplesg\x00\x00\x00\x00\x00\x00\xf0?gffffff\x02@g\x00\x00\x00\x00\x00\x00\x12@s\x1a\x00\x00\x00this is yet another string'
--------------------------------------------------
('this is a string', [1, 2, 3, 4], ('more tuples', 1.0, 2.2999999999999998, 4.5), 'this is yet another string')

使用 marshal 模块处理代码:
import marshal
script = """
print 'hello'
"""
code = compile(script, "<script>", "exec")
data = marshal.dumps(code)
# intermediate format
print type(data), len(data)
print "-"*50
print repr(data)
print "-"*50
exec marshal.loads(data)

输出结果为:
<type 'str'> 102
--------------------------------------------------
'c\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00@\x00\x00\x00s\t\x00\x00\x00d\x00\x00GHd\x01\x00S(\x02\x00\x00\x00t\x05\x00\x00\x00helloN(\x00\x00\x00\x00(\x00\x00\x00\x00(\x00\x00\x00\x00(\x00\x00\x00\x00s\x08\x00\x00\x00<script>s\x08\x00\x00\x00<module>\x02\x00\x00\x00s\x00\x00\x00\x00'
--------------------------------------------------
hello

pickle模块和marshal用法相同, 它比marshal要慢一些, 但它支持用户自定义类, 可以处理类实例, 共享的元素, 以及递归数据结构等. 不过pickle模块不能处理code对象. 还有一个 cPickle 模块, 使用 C 实现了相同的功能, 速度和 marshal 不相上下.
posted on 2009-06-18 22:22 周锐 阅读(1926) 评论(0)  编辑  收藏 所属分类: Python

只有注册用户登录后才能发表评论。


网站导航: