Skip to Content
Binal

I/O

Bytes, files, streams, and async streams

data = packet.encode()
packet = Packet.decode(data)
packet = Packet.decode(memoryview(buffer))

packet = Packet.read_file("packet.bin")
packet.write_file("packet.bin")

Streams

Streams are read incrementally, one record at a time. read() decodes a single record and leaves the stream positioned exactly after it, so consecutive records can be read from the same stream; iter_read() yields records until end of stream. Only the current record is buffered, so a large stream is never slurped into memory.

packet = Packet.read(stream)
packet.write(stream)

for packet in Packet.iter_read(stream):
    process(packet)

A record that makes no progress (a zero-size record with more data after it) raises DecodeError instead of looping forever.

Async streams

The async API works with any async reader/writer pair, e.g. asyncio.StreamReader / asyncio.StreamWriter. read_async() reads one record; iter_read_async() reads records until end of stream. Use the iterator (not repeated read_async() calls) to read several records from one stream, so bytes buffered past one record’s end are kept for the next.

packet = await Packet.read_async(reader)
await packet.write_async(writer)

async for packet in Packet.iter_read_async(reader):
    process(packet)