Python 3.4+structfunction
struct.iter_unpack()
packing and unpacking
Unpacks a buffer of identical records of one format, returning an iterator of tuples, one per record.
Syntax
for fields in struct.iter_unpack(format, buffer): ...
The buffer length must be an exact multiple of calcsize(format), otherwise struct.error is raised right at the call, not at the last record: trim an incomplete tail yourself. Every item is a tuple even for a one-field format, so a flat list of values needs an unpacking loop like for (x,) in ....
Examples
import struct
buf = struct.pack('<4h', 1, 2, 3, 4)
print(list(struct.iter_unpack('<hh', buf))) # → [(1, 2), (3, 4)]
print([x for (x,) in struct.iter_unpack('<h', buf)]) # → [1, 2, 3, 4]
import struct
try:
struct.iter_unpack('<H', b'abc')
except struct.error as e:
print(e) # → iterative unpacking requires a buffer of a multiple of 2 bytes
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy