金源在线客服

在线咨询

QQ在线咨询

QQ咨询

01Jan

Python中的marshal模块和pickle模块

Python中的marshal模块和pickle模块 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, "

上一篇:Django全局context处理器
下一篇:猪八戒网-用python tornado开发类似v2ex.com的网站