Python struct.error
Unpacking a four-byte integer requires a buffer of exactly four bytes.
A simple example
struct.error
- Start with One available byte
- Do this Try to read a complete two-byte field
- Result One byte is missing
Syntax
struct.unpack(">i", packet)
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyRead a stock count from a short record
A stock scanner sends each count as a four-byte integer. A transfer stops after two bytes, so the receiver must request the record again before posting the count to inventory.
import struct
try:
print(struct.unpack(">i", bytes([0, 5]))[0])
except struct.error:
print("Request the complete record")
Request the complete record
The two-byte transfer falls short of the four bytes required for a stock count.
Decode a complete gate count
A counter sends one four-byte record for the entrance. The device format requires a four-byte integer. Request another transmission if the input ends before all four bytes arrive.
Detect a cut-off meter record
A sensor connection closes after the first two bytes of a four-byte record. The device format requires a four-byte integer. Request another transmission if the input ends before all four bytes arrive.
What to watch for
Select a byte order explicitly for a file or network record shared between machines.