posts - 431,  comments - 344,  trackbacks - 0
          marshal模塊使用了簡單的自描述格式(Self-Describing Formats)把不連續(xù)的數(shù)據(jù)組合起來與字符串相互轉(zhuǎn)化, 這樣它們就可以寫入文件或者是在網(wǎng)絡(luò)中傳輸, 對于每個數(shù)據(jù)項目, 格式化后的字符串都包含一種類型代碼, 然后是一個或者多個類型標(biāo)識區(qū)域. 整數(shù)使用小字節(jié)序(little-endian order)儲存, 字符串儲存時和它自身內(nèi)容長度相同(可能包含空字節(jié)), 元組由組成它的對象組合表示. 它支持大多數(shù)的內(nèi)建數(shù)據(jù)類型, 包括code對象. Python自身也使用了這個格式來存儲編譯后代碼(.pyc文件).
          使用 marshal 模塊組合不連續(xù)數(shù)據(jù):
          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)

          輸出結(jié)果為:
          <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)

          輸出結(jié)果為:
          <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要慢一些, 但它支持用戶自定義類, 可以處理類實例, 共享的元素, 以及遞歸數(shù)據(jù)結(jié)構(gòu)等. 不過pickle模塊不能處理code對象. 還有一個 cPickle 模塊, 使用 C 實現(xiàn)了相同的功能, 速度和 marshal 不相上下.
          posted on 2009-06-18 22:22 周銳 閱讀(1968) 評論(0)  編輯  收藏 所屬分類: Python
          主站蜘蛛池模板: 伊金霍洛旗| 荔波县| 原阳县| 长春市| 萝北县| 五大连池市| 固阳县| 平安县| 西乌珠穆沁旗| 台东县| 永吉县| 开封市| 嵩明县| 依安县| 定襄县| 连云港市| 卫辉市| 广昌县| 固安县| 曲沃县| 吉隆县| 蓝山县| 孝感市| 弋阳县| 平定县| 潼南县| 芦溪县| 台东县| 鱼台县| 安庆市| 五华县| 图木舒克市| 平昌县| 大洼县| 应城市| 盐亭县| 达孜县| 台南市| 延庆县| 原阳县| 乳山市|