blob: 6ead9b90c677f3964ff0c3de45df8d6fbf8fe795 [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
Mark Dickinsonbbacb832010-04-12 19:25:32 +000013as Python strings. This can be used in handling binary data stored in files or from network connections, among other sources. It uses
14:ref:`struct-format-strings` as compact descriptions of the layout of the C
15structs and the intended conversion to/from Python values.
16
17.. note::
18
19 The string representation of a given C struct includes padding where
20 necessary by default. This is the same behavior as provided by most
21 C compilers. The padding may be disabled if desired.
22
23Functions and Exceptions
24------------------------
Georg Brandl8ec7f652007-08-15 14:28:01 +000025
26The module defines the following exception and functions:
27
28
29.. exception:: error
30
31 Exception raised on various occasions; argument is a string describing what is
32 wrong.
33
34
35.. function:: pack(fmt, v1, v2, ...)
36
37 Return a string containing the values ``v1, v2, ...`` packed according to the
38 given format. The arguments must match the values required by the format
39 exactly.
40
41
42.. function:: pack_into(fmt, buffer, offset, v1, v2, ...)
43
44 Pack the values ``v1, v2, ...`` according to the given format, write the packed
45 bytes into the writable *buffer* starting at *offset*. Note that the offset is
46 a required argument.
47
48 .. versionadded:: 2.5
49
50
51.. function:: unpack(fmt, string)
52
53 Unpack the string (presumably packed by ``pack(fmt, ...)``) according to the
54 given format. The result is a tuple even if it contains exactly one item. The
55 string must contain exactly the amount of data required by the format
56 (``len(string)`` must equal ``calcsize(fmt)``).
57
58
59.. function:: unpack_from(fmt, buffer[,offset=0])
60
Facundo Batistaeeafb962009-03-04 21:18:17 +000061 Unpack the *buffer* according to the given format. The result is a tuple even
Georg Brandl8ec7f652007-08-15 14:28:01 +000062 if it contains exactly one item. The *buffer* must contain at least the amount
63 of data required by the format (``len(buffer[offset:])`` must be at least
64 ``calcsize(fmt)``).
65
66 .. versionadded:: 2.5
67
68
69.. function:: calcsize(fmt)
70
71 Return the size of the struct (and hence of the string) corresponding to the
72 given format.
73
Mark Dickinsonbbacb832010-04-12 19:25:32 +000074.. _struct-format-strings:
75
76Format Strings
77--------------
78
79Format strings are the mechanism used to specify the expected layout when
80packing and unpacking data. They are built up from format characters, which
81specify the type of data being packed/unpacked. In addition, there are
82special characters for controlling the byte order, size, and alignment.
83
84Format Characters
85^^^^^^^^^^^^^^^^^
86
Georg Brandl8ec7f652007-08-15 14:28:01 +000087Format characters have the following meaning; the conversion between C and
88Python values should be obvious given their types:
89
Mark Dickinsonbbacb832010-04-12 19:25:32 +000090+--------+-------------------------+--------------------+------------+
91| Format | C Type | Python | Notes |
92+========+=========================+====================+============+
93| ``x`` | pad byte | no value | |
94+--------+-------------------------+--------------------+------------+
95| ``c`` | :ctype:`char` | string of length 1 | |
96+--------+-------------------------+--------------------+------------+
97| ``b`` | :ctype:`signed char` | integer | \(3) |
98+--------+-------------------------+--------------------+------------+
99| ``B`` | :ctype:`unsigned char` | integer | \(3) |
100+--------+-------------------------+--------------------+------------+
101| ``?`` | :ctype:`_Bool` | bool | \(1) |
102+--------+-------------------------+--------------------+------------+
103| ``h`` | :ctype:`short` | integer | \(3) |
104+--------+-------------------------+--------------------+------------+
105| ``H`` | :ctype:`unsigned short` | integer | \(3) |
106+--------+-------------------------+--------------------+------------+
107| ``i`` | :ctype:`int` | integer | \(3) |
108+--------+-------------------------+--------------------+------------+
109| ``I`` | :ctype:`unsigned int` | integer or long | \(3) |
110+--------+-------------------------+--------------------+------------+
111| ``l`` | :ctype:`long` | integer | \(3) |
112+--------+-------------------------+--------------------+------------+
113| ``L`` | :ctype:`unsigned long` | long | \(3) |
114+--------+-------------------------+--------------------+------------+
115| ``q`` | :ctype:`long long` | long | \(2),\(3) |
116+--------+-------------------------+--------------------+------------+
117| ``Q`` | :ctype:`unsigned long | long | \(2),\(3) |
118| | long` | | |
119+--------+-------------------------+--------------------+------------+
120| ``f`` | :ctype:`float` | float | |
121+--------+-------------------------+--------------------+------------+
122| ``d`` | :ctype:`double` | float | |
123+--------+-------------------------+--------------------+------------+
124| ``s`` | :ctype:`char[]` | string | |
125+--------+-------------------------+--------------------+------------+
126| ``p`` | :ctype:`char[]` | string | |
127+--------+-------------------------+--------------------+------------+
128| ``P`` | :ctype:`void \*` | long | \(3) |
129+--------+-------------------------+--------------------+------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000130
131Notes:
132
133(1)
Thomas Hellerf3c05592008-03-05 15:34:29 +0000134 The ``'?'`` conversion code corresponds to the :ctype:`_Bool` type defined by
Georg Brandl8ec7f652007-08-15 14:28:01 +0000135 C99. If this type is not available, it is simulated using a :ctype:`char`. In
136 standard mode, it is always represented by one byte.
137
138 .. versionadded:: 2.6
139
140(2)
141 The ``'q'`` and ``'Q'`` conversion codes are available in native mode only if
142 the platform C compiler supports C :ctype:`long long`, or, on Windows,
143 :ctype:`__int64`. They are always available in standard modes.
144
145 .. versionadded:: 2.2
146
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000147(3)
148 When attempting to pack a non-integer using any of the integer conversion
Mark Dickinson4846a8e2010-04-03 14:05:10 +0000149 codes, if the non-integer has a :meth:`__index__` method then that method is
150 called to convert the argument to an integer before packing. If no
151 :meth:`__index__` method exists, or the call to :meth:`__index__` raises
152 :exc:`TypeError`, then the :meth:`__int__` method is tried. However, the use
Ezio Melotti9ccc5812010-04-05 08:16:41 +0000153 of :meth:`__int__` is deprecated, and will raise :exc:`DeprecationWarning`.
Mark Dickinson4846a8e2010-04-03 14:05:10 +0000154
155 .. versionchanged:: 2.7
156 Use of the :meth:`__index__` method for non-integers is new in 2.7.
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000157
158 .. versionchanged:: 2.7
159 Prior to version 2.7, not all integer conversion codes would use the
160 :meth:`__int__` method to convert, and :exc:`DeprecationWarning` was
161 raised only for float arguments.
162
163
Georg Brandl8ec7f652007-08-15 14:28:01 +0000164A format character may be preceded by an integral repeat count. For example,
165the format string ``'4h'`` means exactly the same as ``'hhhh'``.
166
167Whitespace characters between formats are ignored; a count and its format must
168not contain whitespace though.
169
170For the ``'s'`` format character, the count is interpreted as the size of the
171string, not a repeat count like for the other format characters; for example,
172``'10s'`` means a single 10-byte string, while ``'10c'`` means 10 characters.
173For packing, the string is truncated or padded with null bytes as appropriate to
174make it fit. For unpacking, the resulting string always has exactly the
175specified number of bytes. As a special case, ``'0s'`` means a single, empty
176string (while ``'0c'`` means 0 characters).
177
178The ``'p'`` format character encodes a "Pascal string", meaning a short
179variable-length string stored in a fixed number of bytes. The count is the total
180number of bytes stored. The first byte stored is the length of the string, or
181255, whichever is smaller. The bytes of the string follow. If the string
182passed in to :func:`pack` is too long (longer than the count minus 1), only the
183leading count-1 bytes of the string are stored. If the string is shorter than
184count-1, it is padded with null bytes so that exactly count bytes in all are
185used. Note that for :func:`unpack`, the ``'p'`` format character consumes count
186bytes, but that the string returned can never contain more than 255 characters.
187
188For the ``'I'``, ``'L'``, ``'q'`` and ``'Q'`` format characters, the return
189value is a Python long integer.
190
191For the ``'P'`` format character, the return value is a Python integer or long
192integer, depending on the size needed to hold a pointer when it has been cast to
193an integer type. A *NULL* pointer will always be returned as the Python integer
194``0``. When packing pointer-sized values, Python integer or long integer objects
195may be used. For example, the Alpha and Merced processors use 64-bit pointer
196values, meaning a Python long integer will be used to hold the pointer; other
197platforms use 32-bit pointers and will use a Python integer.
198
Thomas Hellerf3c05592008-03-05 15:34:29 +0000199For the ``'?'`` format character, the return value is either :const:`True` or
Georg Brandl8ec7f652007-08-15 14:28:01 +0000200:const:`False`. When packing, the truth value of the argument object is used.
201Either 0 or 1 in the native or standard bool representation will be packed, and
202any non-zero value will be True when unpacking.
203
Mark Dickinsonbbacb832010-04-12 19:25:32 +0000204Byte Order, Size, and Alignment
205^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
206
Georg Brandl8ec7f652007-08-15 14:28:01 +0000207By default, C numbers are represented in the machine's native format and byte
208order, and properly aligned by skipping pad bytes if necessary (according to the
209rules used by the C compiler).
210
211Alternatively, the first character of the format string can be used to indicate
212the byte order, size and alignment of the packed data, according to the
213following table:
214
215+-----------+------------------------+--------------------+
216| Character | Byte order | Size and alignment |
217+===========+========================+====================+
218| ``@`` | native | native |
219+-----------+------------------------+--------------------+
220| ``=`` | native | standard |
221+-----------+------------------------+--------------------+
222| ``<`` | little-endian | standard |
223+-----------+------------------------+--------------------+
224| ``>`` | big-endian | standard |
225+-----------+------------------------+--------------------+
226| ``!`` | network (= big-endian) | standard |
227+-----------+------------------------+--------------------+
228
229If the first character is not one of these, ``'@'`` is assumed.
230
Andrew M. Kuchlingdfd01482010-02-22 15:13:17 +0000231Native byte order is big-endian or little-endian, depending on the host
232system. For example, Intel x86 and AMD64 (x86-64) are little-endian;
233Motorola 68000 and PowerPC G5 are big-endian; ARM and Intel Itanium feature
234switchable endianness (bi-endian). Use ``sys.byteorder`` to check the
235endianness of your system.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000236
237Native size and alignment are determined using the C compiler's
Georg Brandlb19be572007-12-29 10:57:00 +0000238``sizeof`` expression. This is always combined with native byte order.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000239
240Standard size and alignment are as follows: no alignment is required for any
241type (so you have to use pad bytes); :ctype:`short` is 2 bytes; :ctype:`int` and
242:ctype:`long` are 4 bytes; :ctype:`long long` (:ctype:`__int64` on Windows) is 8
243bytes; :ctype:`float` and :ctype:`double` are 32-bit and 64-bit IEEE floating
244point numbers, respectively. :ctype:`_Bool` is 1 byte.
245
246Note the difference between ``'@'`` and ``'='``: both use native byte order, but
247the size and alignment of the latter is standardized.
248
249The form ``'!'`` is available for those poor souls who claim they can't remember
250whether network byte order is big-endian or little-endian.
251
252There is no way to indicate non-native byte order (force byte-swapping); use the
253appropriate choice of ``'<'`` or ``'>'``.
254
255The ``'P'`` format character is only available for the native byte ordering
256(selected as the default or with the ``'@'`` byte order character). The byte
257order character ``'='`` chooses to use little- or big-endian ordering based on
258the host system. The struct module does not interpret this as native ordering,
259so the ``'P'`` format is not available.
260
Mark Dickinsonbbacb832010-04-12 19:25:32 +0000261Notes:
262
263(1) Padding is only automatically added between successive structure members.
264 Never at the beginning of the string encoding and never at the end.
265
266(2) Padding is disabled when using non-native size and alignment, e.g.
267 with '<', '>', '=', and '!'.
268
269(3) To align the end of a structure to the alignment requirement of a
270 particular type, end the format with the code for that type with a repeat
271 count of zero. See :ref:`struct-examples`.
272
273
274.. _struct-examples:
275
276Examples
277^^^^^^^^
278
279.. note::
280 All examples assume a native byte order, size, and alignment with a
281 big-endian machine.
282
283A basic example of packing/unpacking three integers::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000284
285 >>> from struct import *
286 >>> pack('hhl', 1, 2, 3)
287 '\x00\x01\x00\x02\x00\x00\x00\x03'
288 >>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')
289 (1, 2, 3)
290 >>> calcsize('hhl')
291 8
292
Raymond Hettingerf6901e92008-05-23 17:21:44 +0000293Unpacked fields can be named by assigning them to variables or by wrapping
294the result in a named tuple::
295
296 >>> record = 'raymond \x32\x12\x08\x01\x08'
297 >>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)
298
299 >>> from collections import namedtuple
300 >>> Student = namedtuple('Student', 'name serialnum school gradelevel')
301 >>> Student._make(unpack('<10sHHb', s))
302 Student(name='raymond ', serialnum=4658, school=264, gradelevel=8)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000303
Mark Dickinsonbbacb832010-04-12 19:25:32 +0000304The ordering of format characters may have an impact on size since the padding
305needed to satisfy alignment requirements is different::
306
307 >>> pack('ci', '*', 0x12131415)
308 '*\x00\x00\x00\x12\x13\x14\x15'
309 >>> pack('ic', 0x12131415, '*')
310 '\x12\x13\x14\x15*'
311 >>> calcsize('ci')
312 8
313 >>> calcsize('ic')
314 5
315
316The following format ``'llh0l'`` specifies two pad bytes at the end, assuming longs are aligned on 4-byte boundaries::
317
318 >>> pack('llh0l', 1, 2, 3)
319 '\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00'
320
321This only works when native size and alignment are in effect; standard size and
322alignment does not enforce any alignment.
323
324
Georg Brandl8ec7f652007-08-15 14:28:01 +0000325.. seealso::
326
327 Module :mod:`array`
328 Packed binary storage of homogeneous data.
329
330 Module :mod:`xdrlib`
331 Packing and unpacking of XDR data.
332
333
334.. _struct-objects:
335
Mark Dickinsonbbacb832010-04-12 19:25:32 +0000336Objects
337-------
Georg Brandl8ec7f652007-08-15 14:28:01 +0000338
339The :mod:`struct` module also defines the following type:
340
341
342.. class:: Struct(format)
343
344 Return a new Struct object which writes and reads binary data according to the
345 format string *format*. Creating a Struct object once and calling its methods
346 is more efficient than calling the :mod:`struct` functions with the same format
347 since the format string only needs to be compiled once.
348
349 .. versionadded:: 2.5
350
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000351 Compiled Struct objects support the following methods and attributes:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000352
353
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000354 .. method:: pack(v1, v2, ...)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000355
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000356 Identical to the :func:`pack` function, using the compiled format.
357 (``len(result)`` will equal :attr:`self.size`.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000358
359
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000360 .. method:: pack_into(buffer, offset, v1, v2, ...)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000361
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000362 Identical to the :func:`pack_into` function, using the compiled format.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000363
364
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000365 .. method:: unpack(string)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000366
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000367 Identical to the :func:`unpack` function, using the compiled format.
368 (``len(string)`` must equal :attr:`self.size`).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000369
370
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000371 .. method:: unpack_from(buffer[, offset=0])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000372
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000373 Identical to the :func:`unpack_from` function, using the compiled format.
374 (``len(buffer[offset:])`` must be at least :attr:`self.size`).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000375
376
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000377 .. attribute:: format
Georg Brandl8ec7f652007-08-15 14:28:01 +0000378
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000379 The format string used to construct this Struct object.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000380
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000381 .. attribute:: size
Georg Brandlb7a837d2007-08-23 21:21:36 +0000382
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000383 The calculated size of the struct (and hence of the string) corresponding
384 to :attr:`format`.
Georg Brandlb7a837d2007-08-23 21:21:36 +0000385