文章来自《Python cookbook》.

翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!

::-- rings [2005-09-20 13:32:49]

1. 描述

8.2 Serializing Data Using the marshal Module 使用marshal模块序列化数据

1.1. 问题 Problem

You have a Python data structure composed of only fundamental Python objects (e.g., lists, tuples, numbers, and strings, but no classes, instances, etc.), and you want to serialize it and reconstruct it later as fast as possible.

你有一个仅仅包括基本python对象组成的数据结构(如,lists,tuples, number, 和string , 但是不包括classes, instances 等)并且,你想在以后能尽可能快的序列化和重建它。

1.2. 解决 Solution

If you know that your data is composed entirely of fundamental Python objects, the lowest-level, fastest approach to serializing it (i.e., turning it into a string of bytes and later reconstructing it from such a string) is via the marshal module. Suppose that data is composed of only elementary Python data types. For example: 如果你知道你的数据结构是完全由基本的python对象组成,最低级,快速的序列化它的方法是(如,转化它到一串字节,以后在从哪个串中重构它)通过marshal模块。假定数据是仅仅由python数据类型元素组成,例如:

   1 data = {12:'twelve', 'feep':list('ciao'), 1.23:4+5j, (1,2,3):u'wer'}

You can serialize data to a byte string at top speed as follows: 象下列那样,你能够以极快的速度序列化数据到一个字节串中:

import marshal
bytes = marshal.dumps(data)

You can now sling bytes around as you wish (e.g., send it across a network, put it as a BLOB in a database, etc.), as long as you keep its arbitrary binary bytes intact. Then you can reconstruct the data any time you'd like: 你现在能够象你希望的那样把这些字节投到任何地方(如,通过网络发送它,把它作为一个BLOB放到一个数据库中去。等等)只要你保持它的任意的二进制字节的完整。那么你就能在任何时候你想要的时候重构数据:

redata = marshal.loads(bytes)

1.3. 讨论 Discussion

...

1.4. 参考 See Also


CategoryCookbook 网页分类