7.1. struct
— Interpret bytes as packed binary data
Source code: Lib/struct.py
This module performs conversions between Python values and C structs represented as Python bytes
objects. This can be used in handling binary data stored in files or from network connections, among other sources. It uses Format Strings as compact descriptions of the layout of the C structs and the intended conversion to/from Python values.
Note
By default, the result of packing a given C struct includes pad bytes in order to maintain proper alignment for the C types involved; similarly, alignment is taken into account when unpacking. This behavior is chosen so that the bytes of a packed struct correspond exactly to the layout in memory of the corresponding C struct. To handle platform-independent data formats or omit implicit pad bytes, use standard
size and alignment instead of native
size and alignment: see Byte Order, Size, and Alignment for details.
Several struct
functions (and methods of Struct
) take a buffer argument. This refers to objects that implement the Buffer Protocol and provide either a readable or read-writable buffer. The most common types used for that purpose are bytes
and bytearray
, but many other types that can be viewed as an array of bytes implement the buffer protocol, so that they can be read/filled without additional copying from a bytes
object.
7.1.1. Functions and Exceptions
The module defines the following exception and functions:
-
exception
-
Exception raised on various occasions; argument is a string describing what is wrong.
struct.
error
-
Return a bytes object containing the values v1, v2, ... packed according to the format string fmt. The arguments must match the values required by the format exactly.
struct.
pack
(
fmt,
v1,
v2,
...
)
-
Pack the values v1, v2, ... according to the format string fmt and write the packed bytes into the writable buffer buffer starting at position offset. Note that offset is a required argument.
struct.
pack_into
(
fmt,
buffer,
offset,
v1,
v2,
...
)
-
Unpack from the buffer buffer (presumably packed by
pack(fmt, ...)
) according to the format string fmt. The result is a tuple even if it contains exactly one item. The buffer’s size in bytes must match the size required by the format, as reflected bycalcsize()
.
struct.
unpack
(
fmt,
buffer
)
-
Unpack from buffer starting at position offset, according to the format string fmt. The result is a tuple even if it contains exactly one item. The buffer’s size in bytes, minus offset, must be at least the size required by the format, as reflected by
calcsize()
.
struct.
unpack_from
(
fmt,
buffer,
offset=0
)