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
周銳 閱讀(1972)
評論(0) 編輯 收藏 所屬分類:
Python