blob: ea6b4163ff826c8a1961061983a354c0cd540082 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`struct` --- Interpret strings as packed binary data
3=========================================================
4
5.. module:: struct
6 :synopsis: Interpret strings as packed binary data.
7
8.. index::
9 pair: C; structures
10 triple: packing; binary; data
11
12This module performs conversions between Python values and C structs represented
13as Python strings. It uses :dfn:`format strings` (explained below) as compact
14descriptions of the lay-out of the C structs and the intended conversion to/from
15Python values. This can be used in handling binary data stored in files or from
16network connections, among other sources.
17
18The module defines the following exception and functions:
19
20
21.. exception:: error
22
23 Exception raised on various occasions; argument is a string describing what is
24 wrong.
25
26
27.. function:: pack(fmt, v1, v2, ...)
28
29 Return a string containing the values ``v1, v2, ...`` packed according to the
30 given format. The arguments must match the values required by the format
31 exactly.
32
33
34.. function:: pack_into(fmt, buffer, offset, v1, v2, ...)
35
36 Pack the values ``v1, v2, ...`` according to the given format, write the packed
37 bytes into the writable *buffer* starting at *offset*. Note that the offset is
38 a required argument.
39
40 .. versionadded:: 2.5
41
42
43.. function:: unpack(fmt, string)
44
45 Unpack the string (presumably packed by ``pack(fmt, ...)``) according to the
46 given format. The result is a tuple even if it contains exactly one item. The
47 string must contain exactly the amount of data required by the format
48 (``len(string)`` must equal ``calcsize(fmt)``).
49
50
51.. function:: unpack_from(fmt, buffer[,offset=0])
52
Facundo Batistaeeafb962009-03-04 21:18:17 +000053 Unpack the *buffer* according to the given format. The result is a tuple even
Georg Brandl8ec7f652007-08-15 14:28:01 +000054 if it contains exactly one item. The *buffer* must contain at least the amount
55 of data required by the format (``len(buffer[offset:])`` must be at least
56 ``calcsize(fmt)``).
57
58 .. versionadded:: 2.5
59
60
61.. function:: calcsize(fmt)
62
63 Return the size of the struct (and hence of the string) corresponding to the
64 given format.
65
66Format characters have the following meaning; the conversion between C and
67Python values should be obvious given their types:
68
69+--------+-------------------------+--------------------+-------+
70| Format | C Type | Python | Notes |
71+========+=========================+====================+=======+
72| ``x`` | pad byte | no value | |
73+--------+-------------------------+--------------------+-------+
74| ``c`` | :ctype:`char` | string of length 1 | |
75+--------+-------------------------+--------------------+-------+
76| ``b`` | :ctype:`signed char` | integer | |
77+--------+-------------------------+--------------------+-------+
78| ``B`` | :ctype:`unsigned char` | integer | |
79+--------+-------------------------+--------------------+-------+
Thomas Hellerf3c05592008-03-05 15:34:29 +000080| ``?`` | :ctype:`_Bool` | bool | \(1) |
Georg Brandl8ec7f652007-08-15 14:28:01 +000081+--------+-------------------------+--------------------+-------+
82| ``h`` | :ctype:`short` | integer | |
83+--------+-------------------------+--------------------+-------+
84| ``H`` | :ctype:`unsigned short` | integer | |
85+--------+-------------------------+--------------------+-------+
86| ``i`` | :ctype:`int` | integer | |
87+--------+-------------------------+--------------------+-------+
Gregory P. Smith7b7ce782008-01-24 09:38:26 +000088| ``I`` | :ctype:`unsigned int` | integer or long | |
Georg Brandl8ec7f652007-08-15 14:28:01 +000089+--------+-------------------------+--------------------+-------+
90| ``l`` | :ctype:`long` | integer | |
91+--------+-------------------------+--------------------+-------+
92| ``L`` | :ctype:`unsigned long` | long | |
93+--------+-------------------------+--------------------+-------+
94| ``q`` | :ctype:`long long` | long | \(2) |
95+--------+-------------------------+--------------------+-------+
96| ``Q`` | :ctype:`unsigned long | long | \(2) |
97| | long` | | |
98+--------+-------------------------+--------------------+-------+
99| ``f`` | :ctype:`float` | float | |
100+--------+-------------------------+--------------------+-------+
101| ``d`` | :ctype:`double` | float | |
102+--------+-------------------------+--------------------+-------+
103| ``s`` | :ctype:`char[]` | string | |
104+--------+-------------------------+--------------------+-------+
105| ``p`` | :ctype:`char[]` | string | |
106+--------+-------------------------+--------------------+-------+
Gregory P. Smith7b7ce782008-01-24 09:38:26 +0000107| ``P`` | :ctype:`void \*` | long | |
Georg Brandl8ec7f652007-08-15 14:28:01 +0000108+--------+-------------------------+--------------------+-------+
109
110Notes:
111
112(1)
Thomas Hellerf3c05592008-03-05 15:34:29 +0000113 The ``'?'`` conversion code corresponds to the :ctype:`_Bool` type defined by
Georg Brandl8ec7f652007-08-15 14:28:01 +0000114 C99. If this type is not available, it is simulated using a :ctype:`char`. In
115 standard mode, it is always represented by one byte.
116
117 .. versionadded:: 2.6
118
119(2)
120 The ``'q'`` and ``'Q'`` conversion codes are available in native mode only if
121 the platform C compiler supports C :ctype:`long long`, or, on Windows,
122 :ctype:`__int64`. They are always available in standard modes.
123
124 .. versionadded:: 2.2
125
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000126(3)
127 When attempting to pack a non-integer using any of the integer conversion
Mark Dickinson4846a8e2010-04-03 14:05:10 +0000128 codes, if the non-integer has a :meth:`__index__` method then that method is
129 called to convert the argument to an integer before packing. If no
130 :meth:`__index__` method exists, or the call to :meth:`__index__` raises
131 :exc:`TypeError`, then the :meth:`__int__` method is tried. However, the use
132 of `__int__` is deprecated, and will raise :exc:`DeprecationWarning`.
133
134 .. versionchanged:: 2.7
135 Use of the :meth:`__index__` method for non-integers is new in 2.7.
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000136
137 .. versionchanged:: 2.7
138 Prior to version 2.7, not all integer conversion codes would use the
139 :meth:`__int__` method to convert, and :exc:`DeprecationWarning` was
140 raised only for float arguments.
141
142
Georg Brandl8ec7f652007-08-15 14:28:01 +0000143A format character may be preceded by an integral repeat count. For example,
144the format string ``'4h'`` means exactly the same as ``'hhhh'``.
145
146Whitespace characters between formats are ignored; a count and its format must
147not contain whitespace though.
148
149For the ``'s'`` format character, the count is interpreted as the size of the
150string, not a repeat count like for the other format characters; for example,
151``'10s'`` means a single 10-byte string, while ``'10c'`` means 10 characters.
152For packing, the string is truncated or padded with null bytes as appropriate to
153make it fit. For unpacking, the resulting string always has exactly the
154specified number of bytes. As a special case, ``'0s'`` means a single, empty
155string (while ``'0c'`` means 0 characters).
156
157The ``'p'`` format character encodes a "Pascal string", meaning a short
158variable-length string stored in a fixed number of bytes. The count is the total
159number of bytes stored. The first byte stored is the length of the string, or
160255, whichever is smaller. The bytes of the string follow. If the string
161passed in to :func:`pack` is too long (longer than the count minus 1), only the
162leading count-1 bytes of the string are stored. If the string is shorter than
163count-1, it is padded with null bytes so that exactly count bytes in all are
164used. Note that for :func:`unpack`, the ``'p'`` format character consumes count
165bytes, but that the string returned can never contain more than 255 characters.
166
167For the ``'I'``, ``'L'``, ``'q'`` and ``'Q'`` format characters, the return
168value is a Python long integer.
169
170For the ``'P'`` format character, the return value is a Python integer or long
171integer, depending on the size needed to hold a pointer when it has been cast to
172an integer type. A *NULL* pointer will always be returned as the Python integer
173``0``. When packing pointer-sized values, Python integer or long integer objects
174may be used. For example, the Alpha and Merced processors use 64-bit pointer
175values, meaning a Python long integer will be used to hold the pointer; other
176platforms use 32-bit pointers and will use a Python integer.
177
Thomas Hellerf3c05592008-03-05 15:34:29 +0000178For the ``'?'`` format character, the return value is either :const:`True` or
Georg Brandl8ec7f652007-08-15 14:28:01 +0000179:const:`False`. When packing, the truth value of the argument object is used.
180Either 0 or 1 in the native or standard bool representation will be packed, and
181any non-zero value will be True when unpacking.
182
183By default, C numbers are represented in the machine's native format and byte
184order, and properly aligned by skipping pad bytes if necessary (according to the
185rules used by the C compiler).
186
187Alternatively, the first character of the format string can be used to indicate
188the byte order, size and alignment of the packed data, according to the
189following table:
190
191+-----------+------------------------+--------------------+
192| Character | Byte order | Size and alignment |
193+===========+========================+====================+
194| ``@`` | native | native |
195+-----------+------------------------+--------------------+
196| ``=`` | native | standard |
197+-----------+------------------------+--------------------+
198| ``<`` | little-endian | standard |
199+-----------+------------------------+--------------------+
200| ``>`` | big-endian | standard |
201+-----------+------------------------+--------------------+
202| ``!`` | network (= big-endian) | standard |
203+-----------+------------------------+--------------------+
204
205If the first character is not one of these, ``'@'`` is assumed.
206
Andrew M. Kuchlingdfd01482010-02-22 15:13:17 +0000207Native byte order is big-endian or little-endian, depending on the host
208system. For example, Intel x86 and AMD64 (x86-64) are little-endian;
209Motorola 68000 and PowerPC G5 are big-endian; ARM and Intel Itanium feature
210switchable endianness (bi-endian). Use ``sys.byteorder`` to check the
211endianness of your system.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000212
213Native size and alignment are determined using the C compiler's
Georg Brandlb19be572007-12-29 10:57:00 +0000214``sizeof`` expression. This is always combined with native byte order.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000215
216Standard size and alignment are as follows: no alignment is required for any
217type (so you have to use pad bytes); :ctype:`short` is 2 bytes; :ctype:`int` and
218:ctype:`long` are 4 bytes; :ctype:`long long` (:ctype:`__int64` on Windows) is 8
219bytes; :ctype:`float` and :ctype:`double` are 32-bit and 64-bit IEEE floating
220point numbers, respectively. :ctype:`_Bool` is 1 byte.
221
222Note the difference between ``'@'`` and ``'='``: both use native byte order, but
223the size and alignment of the latter is standardized.
224
225The form ``'!'`` is available for those poor souls who claim they can't remember
226whether network byte order is big-endian or little-endian.
227
228There is no way to indicate non-native byte order (force byte-swapping); use the
229appropriate choice of ``'<'`` or ``'>'``.
230
231The ``'P'`` format character is only available for the native byte ordering
232(selected as the default or with the ``'@'`` byte order character). The byte
233order character ``'='`` chooses to use little- or big-endian ordering based on
234the host system. The struct module does not interpret this as native ordering,
235so the ``'P'`` format is not available.
236
237Examples (all using native byte order, size and alignment, on a big-endian
238machine)::
239
240 >>> from struct import *
241 >>> pack('hhl', 1, 2, 3)
242 '\x00\x01\x00\x02\x00\x00\x00\x03'
243 >>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')
244 (1, 2, 3)
245 >>> calcsize('hhl')
246 8
247
248Hint: to align the end of a structure to the alignment requirement of a
249particular type, end the format with the code for that type with a repeat count
250of zero. For example, the format ``'llh0l'`` specifies two pad bytes at the
251end, assuming longs are aligned on 4-byte boundaries. This only works when
252native size and alignment are in effect; standard size and alignment does not
253enforce any alignment.
254
Raymond Hettingerf6901e92008-05-23 17:21:44 +0000255Unpacked fields can be named by assigning them to variables or by wrapping
256the result in a named tuple::
257
258 >>> record = 'raymond \x32\x12\x08\x01\x08'
259 >>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)
260
261 >>> from collections import namedtuple
262 >>> Student = namedtuple('Student', 'name serialnum school gradelevel')
263 >>> Student._make(unpack('<10sHHb', s))
264 Student(name='raymond ', serialnum=4658, school=264, gradelevel=8)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000265
266.. seealso::
267
268 Module :mod:`array`
269 Packed binary storage of homogeneous data.
270
271 Module :mod:`xdrlib`
272 Packing and unpacking of XDR data.
273
274
275.. _struct-objects:
276
277Struct Objects
278--------------
279
280The :mod:`struct` module also defines the following type:
281
282
283.. class:: Struct(format)
284
285 Return a new Struct object which writes and reads binary data according to the
286 format string *format*. Creating a Struct object once and calling its methods
287 is more efficient than calling the :mod:`struct` functions with the same format
288 since the format string only needs to be compiled once.
289
290 .. versionadded:: 2.5
291
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000292 Compiled Struct objects support the following methods and attributes:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000293
294
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000295 .. method:: pack(v1, v2, ...)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000296
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000297 Identical to the :func:`pack` function, using the compiled format.
298 (``len(result)`` will equal :attr:`self.size`.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000299
300
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000301 .. method:: pack_into(buffer, offset, v1, v2, ...)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000302
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000303 Identical to the :func:`pack_into` function, using the compiled format.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000304
305
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000306 .. method:: unpack(string)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000307
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000308 Identical to the :func:`unpack` function, using the compiled format.
309 (``len(string)`` must equal :attr:`self.size`).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000310
311
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000312 .. method:: unpack_from(buffer[, offset=0])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000313
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000314 Identical to the :func:`unpack_from` function, using the compiled format.
315 (``len(buffer[offset:])`` must be at least :attr:`self.size`).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000316
317
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000318 .. attribute:: format
Georg Brandl8ec7f652007-08-15 14:28:01 +0000319
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000320 The format string used to construct this Struct object.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000321
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000322 .. attribute:: size
Georg Brandlb7a837d2007-08-23 21:21:36 +0000323
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000324 The calculated size of the struct (and hence of the string) corresponding
325 to :attr:`format`.
Georg Brandlb7a837d2007-08-23 21:21:36 +0000326