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