The marshal Module

The marshal module is used to serialize data—that is, convert data to and from character strings, so that they can be stored on file or sent over a network. Example 4-9 illustrates this.

The marshal module uses a simple self-describing data format. For each data item, the marshalled string contains a type code, followed by one or more type-specific fields. Integers are stored in little-endian order, strings are stored as length fields followed by the strings’ contents (which can include null bytes), tuples are stored as length fields followed by the objects that make up each tuple, etc.

Example 4-9. Using the marshal Module to Serialize Data

File: marshal-example-1.py

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 'string'> 118
--------------------------------------------------
'(04000000s20000000this is a string
[04000000i01000000i02000000
i03000000i04000000(04000000
s13000000more tuplesf031.0f032.3f034.
5s32000000this is yet another string'
--------------------------------------------------
('this is a string', [1, 2, 3, 4], ('more tuples',
1.0, 2.3, 4.5), 'this is yet another string')

The marshal module can also handle code objects (it’s used to store precompiled Python modules). Example 4-10 demonstrates.

Example 4-10. Using the marshal Module to Serialize Code

File: marshal-example-2.py

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 'string'> 81
--------------------------------------------------
'c0000000001000000s1700000
017700001770200d0000GHd0100S(0
2000000s05000000helloN(000000
000(00000000s10000000<script>s01
000000?0200s00000000'
--------------------------------------------------
hello
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.205.99