/Doc/library/struct.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 307 lines · 221 code · 86 blank · 0 comment · 0 complexity · 15ade3adf9b6aebcbc19ca7bc5600f75 MD5 · raw file

  1. :mod:`struct` --- Interpret strings as packed binary data
  2. =========================================================
  3. .. module:: struct
  4. :synopsis: Interpret strings as packed binary data.
  5. .. index::
  6. pair: C; structures
  7. triple: packing; binary; data
  8. This module performs conversions between Python values and C structs represented
  9. as Python strings. It uses :dfn:`format strings` (explained below) as compact
  10. descriptions of the lay-out of the C structs and the intended conversion to/from
  11. Python values. This can be used in handling binary data stored in files or from
  12. network connections, among other sources.
  13. The module defines the following exception and functions:
  14. .. exception:: error
  15. Exception raised on various occasions; argument is a string describing what is
  16. wrong.
  17. .. function:: pack(fmt, v1, v2, ...)
  18. Return a string containing the values ``v1, v2, ...`` packed according to the
  19. given format. The arguments must match the values required by the format
  20. exactly.
  21. .. function:: pack_into(fmt, buffer, offset, v1, v2, ...)
  22. Pack the values ``v1, v2, ...`` according to the given format, write the packed
  23. bytes into the writable *buffer* starting at *offset*. Note that the offset is
  24. a required argument.
  25. .. versionadded:: 2.5
  26. .. function:: unpack(fmt, string)
  27. Unpack the string (presumably packed by ``pack(fmt, ...)``) according to the
  28. given format. The result is a tuple even if it contains exactly one item. The
  29. string must contain exactly the amount of data required by the format
  30. (``len(string)`` must equal ``calcsize(fmt)``).
  31. .. function:: unpack_from(fmt, buffer[,offset=0])
  32. Unpack the *buffer* according to tthe given format. The result is a tuple even
  33. if it contains exactly one item. The *buffer* must contain at least the amount
  34. of data required by the format (``len(buffer[offset:])`` must be at least
  35. ``calcsize(fmt)``).
  36. .. versionadded:: 2.5
  37. .. function:: calcsize(fmt)
  38. Return the size of the struct (and hence of the string) corresponding to the
  39. given format.
  40. Format characters have the following meaning; the conversion between C and
  41. Python values should be obvious given their types:
  42. +--------+-------------------------+--------------------+-------+
  43. | Format | C Type | Python | Notes |
  44. +========+=========================+====================+=======+
  45. | ``x`` | pad byte | no value | |
  46. +--------+-------------------------+--------------------+-------+
  47. | ``c`` | :ctype:`char` | string of length 1 | |
  48. +--------+-------------------------+--------------------+-------+
  49. | ``b`` | :ctype:`signed char` | integer | |
  50. +--------+-------------------------+--------------------+-------+
  51. | ``B`` | :ctype:`unsigned char` | integer | |
  52. +--------+-------------------------+--------------------+-------+
  53. | ``?`` | :ctype:`_Bool` | bool | \(1) |
  54. +--------+-------------------------+--------------------+-------+
  55. | ``h`` | :ctype:`short` | integer | |
  56. +--------+-------------------------+--------------------+-------+
  57. | ``H`` | :ctype:`unsigned short` | integer | |
  58. +--------+-------------------------+--------------------+-------+
  59. | ``i`` | :ctype:`int` | integer | |
  60. +--------+-------------------------+--------------------+-------+
  61. | ``I`` | :ctype:`unsigned int` | integer or long | |
  62. +--------+-------------------------+--------------------+-------+
  63. | ``l`` | :ctype:`long` | integer | |
  64. +--------+-------------------------+--------------------+-------+
  65. | ``L`` | :ctype:`unsigned long` | long | |
  66. +--------+-------------------------+--------------------+-------+
  67. | ``q`` | :ctype:`long long` | long | \(2) |
  68. +--------+-------------------------+--------------------+-------+
  69. | ``Q`` | :ctype:`unsigned long | long | \(2) |
  70. | | long` | | |
  71. +--------+-------------------------+--------------------+-------+
  72. | ``f`` | :ctype:`float` | float | |
  73. +--------+-------------------------+--------------------+-------+
  74. | ``d`` | :ctype:`double` | float | |
  75. +--------+-------------------------+--------------------+-------+
  76. | ``s`` | :ctype:`char[]` | string | |
  77. +--------+-------------------------+--------------------+-------+
  78. | ``p`` | :ctype:`char[]` | string | |
  79. +--------+-------------------------+--------------------+-------+
  80. | ``P`` | :ctype:`void \*` | long | |
  81. +--------+-------------------------+--------------------+-------+
  82. Notes:
  83. (1)
  84. The ``'?'`` conversion code corresponds to the :ctype:`_Bool` type defined by
  85. C99. If this type is not available, it is simulated using a :ctype:`char`. In
  86. standard mode, it is always represented by one byte.
  87. .. versionadded:: 2.6
  88. (2)
  89. The ``'q'`` and ``'Q'`` conversion codes are available in native mode only if
  90. the platform C compiler supports C :ctype:`long long`, or, on Windows,
  91. :ctype:`__int64`. They are always available in standard modes.
  92. .. versionadded:: 2.2
  93. A format character may be preceded by an integral repeat count. For example,
  94. the format string ``'4h'`` means exactly the same as ``'hhhh'``.
  95. Whitespace characters between formats are ignored; a count and its format must
  96. not contain whitespace though.
  97. For the ``'s'`` format character, the count is interpreted as the size of the
  98. string, not a repeat count like for the other format characters; for example,
  99. ``'10s'`` means a single 10-byte string, while ``'10c'`` means 10 characters.
  100. For packing, the string is truncated or padded with null bytes as appropriate to
  101. make it fit. For unpacking, the resulting string always has exactly the
  102. specified number of bytes. As a special case, ``'0s'`` means a single, empty
  103. string (while ``'0c'`` means 0 characters).
  104. The ``'p'`` format character encodes a "Pascal string", meaning a short
  105. variable-length string stored in a fixed number of bytes. The count is the total
  106. number of bytes stored. The first byte stored is the length of the string, or
  107. 255, whichever is smaller. The bytes of the string follow. If the string
  108. passed in to :func:`pack` is too long (longer than the count minus 1), only the
  109. leading count-1 bytes of the string are stored. If the string is shorter than
  110. count-1, it is padded with null bytes so that exactly count bytes in all are
  111. used. Note that for :func:`unpack`, the ``'p'`` format character consumes count
  112. bytes, but that the string returned can never contain more than 255 characters.
  113. For the ``'I'``, ``'L'``, ``'q'`` and ``'Q'`` format characters, the return
  114. value is a Python long integer.
  115. For the ``'P'`` format character, the return value is a Python integer or long
  116. integer, depending on the size needed to hold a pointer when it has been cast to
  117. an integer type. A *NULL* pointer will always be returned as the Python integer
  118. ``0``. When packing pointer-sized values, Python integer or long integer objects
  119. may be used. For example, the Alpha and Merced processors use 64-bit pointer
  120. values, meaning a Python long integer will be used to hold the pointer; other
  121. platforms use 32-bit pointers and will use a Python integer.
  122. For the ``'?'`` format character, the return value is either :const:`True` or
  123. :const:`False`. When packing, the truth value of the argument object is used.
  124. Either 0 or 1 in the native or standard bool representation will be packed, and
  125. any non-zero value will be True when unpacking.
  126. By default, C numbers are represented in the machine's native format and byte
  127. order, and properly aligned by skipping pad bytes if necessary (according to the
  128. rules used by the C compiler).
  129. Alternatively, the first character of the format string can be used to indicate
  130. the byte order, size and alignment of the packed data, according to the
  131. following table:
  132. +-----------+------------------------+--------------------+
  133. | Character | Byte order | Size and alignment |
  134. +===========+========================+====================+
  135. | ``@`` | native | native |
  136. +-----------+------------------------+--------------------+
  137. | ``=`` | native | standard |
  138. +-----------+------------------------+--------------------+
  139. | ``<`` | little-endian | standard |
  140. +-----------+------------------------+--------------------+
  141. | ``>`` | big-endian | standard |
  142. +-----------+------------------------+--------------------+
  143. | ``!`` | network (= big-endian) | standard |
  144. +-----------+------------------------+--------------------+
  145. If the first character is not one of these, ``'@'`` is assumed.
  146. Native byte order is big-endian or little-endian, depending on the host system.
  147. For example, Motorola and Sun processors are big-endian; Intel and DEC
  148. processors are little-endian.
  149. Native size and alignment are determined using the C compiler's
  150. ``sizeof`` expression. This is always combined with native byte order.
  151. Standard size and alignment are as follows: no alignment is required for any
  152. type (so you have to use pad bytes); :ctype:`short` is 2 bytes; :ctype:`int` and
  153. :ctype:`long` are 4 bytes; :ctype:`long long` (:ctype:`__int64` on Windows) is 8
  154. bytes; :ctype:`float` and :ctype:`double` are 32-bit and 64-bit IEEE floating
  155. point numbers, respectively. :ctype:`_Bool` is 1 byte.
  156. Note the difference between ``'@'`` and ``'='``: both use native byte order, but
  157. the size and alignment of the latter is standardized.
  158. The form ``'!'`` is available for those poor souls who claim they can't remember
  159. whether network byte order is big-endian or little-endian.
  160. There is no way to indicate non-native byte order (force byte-swapping); use the
  161. appropriate choice of ``'<'`` or ``'>'``.
  162. The ``'P'`` format character is only available for the native byte ordering
  163. (selected as the default or with the ``'@'`` byte order character). The byte
  164. order character ``'='`` chooses to use little- or big-endian ordering based on
  165. the host system. The struct module does not interpret this as native ordering,
  166. so the ``'P'`` format is not available.
  167. Examples (all using native byte order, size and alignment, on a big-endian
  168. machine)::
  169. >>> from struct import *
  170. >>> pack('hhl', 1, 2, 3)
  171. '\x00\x01\x00\x02\x00\x00\x00\x03'
  172. >>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')
  173. (1, 2, 3)
  174. >>> calcsize('hhl')
  175. 8
  176. Hint: to align the end of a structure to the alignment requirement of a
  177. particular type, end the format with the code for that type with a repeat count
  178. of zero. For example, the format ``'llh0l'`` specifies two pad bytes at the
  179. end, assuming longs are aligned on 4-byte boundaries. This only works when
  180. native size and alignment are in effect; standard size and alignment does not
  181. enforce any alignment.
  182. Unpacked fields can be named by assigning them to variables or by wrapping
  183. the result in a named tuple::
  184. >>> record = 'raymond \x32\x12\x08\x01\x08'
  185. >>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)
  186. >>> from collections import namedtuple
  187. >>> Student = namedtuple('Student', 'name serialnum school gradelevel')
  188. >>> Student._make(unpack('<10sHHb', s))
  189. Student(name='raymond ', serialnum=4658, school=264, gradelevel=8)
  190. .. seealso::
  191. Module :mod:`array`
  192. Packed binary storage of homogeneous data.
  193. Module :mod:`xdrlib`
  194. Packing and unpacking of XDR data.
  195. .. _struct-objects:
  196. Struct Objects
  197. --------------
  198. The :mod:`struct` module also defines the following type:
  199. .. class:: Struct(format)
  200. Return a new Struct object which writes and reads binary data according to the
  201. format string *format*. Creating a Struct object once and calling its methods
  202. is more efficient than calling the :mod:`struct` functions with the same format
  203. since the format string only needs to be compiled once.
  204. .. versionadded:: 2.5
  205. Compiled Struct objects support the following methods and attributes:
  206. .. method:: pack(v1, v2, ...)
  207. Identical to the :func:`pack` function, using the compiled format.
  208. (``len(result)`` will equal :attr:`self.size`.)
  209. .. method:: pack_into(buffer, offset, v1, v2, ...)
  210. Identical to the :func:`pack_into` function, using the compiled format.
  211. .. method:: unpack(string)
  212. Identical to the :func:`unpack` function, using the compiled format.
  213. (``len(string)`` must equal :attr:`self.size`).
  214. .. method:: unpack_from(buffer[, offset=0])
  215. Identical to the :func:`unpack_from` function, using the compiled format.
  216. (``len(buffer[offset:])`` must be at least :attr:`self.size`).
  217. .. attribute:: format
  218. The format string used to construct this Struct object.
  219. .. attribute:: size
  220. The calculated size of the struct (and hence of the string) corresponding
  221. to :attr:`format`.