liveBook · Manning

Stream reader

As explained in Python Concurrency with asyncio

A stream reader is an object that provides asynchronous operations for receiving data from a network stream.

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

How Python Concurrency with asyncio covers it

How deep it goes
Explains readline(), read(), protocol connections, and practical integrations, while deferring lower-level transport implementation details.
Examples
Demonstrates HTTP response reading, asynchronous standard input, echo servers, and piped subprocess output.
What it assumes
Assumes basic asyncio coroutines and tasks, while contrasting stream APIs with lower-level transports and protocols.
What you can do after
Build asynchronous clients and applications that consume network, console, server, or subprocess data without blocking the event loop.
How it connects
Connects StreamReader with asyncio, StreamWriter, transports and protocols, event loops, servers, pipes, and subprocesses.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Concurrency with asyncio. The section links point to the parts of the book it draws on.