A stream reader is an object that provides asynchronous operations for receiving data from a network stream. Its coroutines wait for data without blocking the event loop, making it useful for responsive clients, command-line programs, and servers. section 8.0 section 8.3
Use a stream reader to:
- Read one line at a time with readline(), which waits until a line arrives or the stream ends. section 8.3
- Read a specified number of bytes with read(), then decode the received data when appropriate. section 8.3
- Receive console input asynchronously by connecting sys.stdin through StreamReaderProtocol and connect_read_pipe(). section 8.4
- Consume subprocess output through a StreamReader when stdout is configured as asyncio.subprocess.PIPE. section 13.1.1
StreamReader belongs to asyncio’s higher-level streams API. asyncio.open_connection() creates a reader and a StreamWriter together: the writer sends a request, while the reader asynchronously receives the response. Compared with transports and protocols, streams avoid repetitive low-level socket handling. section 8.3
Read an HTTP response
A line-oriented async generator can repeatedly await stream_reader.readline(), decode each nonempty response line, and stop when readline() returns an empty value. A connection created with asyncio.open_connection() supplies the reader; the paired writer sends the encoded HTTP request and drains its buffer. section 8.3
Keep input responsive
Replacing blocking input() with await stdin_reader.readline() lets a command-line program receive input while background delay tasks continue running. The same reader-and-writer pairing supports client callbacks in an asyncio server. section 8.5
