liveBook · Manning

StreamReaderProtocol

As explained in Python Concurrency with asyncio

StreamReaderProtocol is an asyncio protocol implementation that forwards received stream data to a StreamReader.

StreamReaderProtocol connects an asyncio protocol to a StreamReader. It receives data from a stream, delegates that data to the reader, and exposes reader operations such as readline(). section 8.4

For non-blocking standard input, create a StreamReader, wrap it in StreamReaderProtocol, and pass the protocol through connect_read_pipe. This lets input wait asynchronously without blocking the event loop. Windows sys.stdin requires a separate thread because connect_read_pipe does not work there. section 8.4

Listing 8.5 An asynchronous standard input reader
import asyncio
from asyncio import StreamReader
import sys
 
 
async def create_stdin_reader() -> StreamReader:
    stream_reader = asyncio.StreamReader()
    protocol = asyncio.StreamReaderProtocol(stream_reader)
    loop = asyncio.get_running_loop()
    await loop.connect_read_pipe(lambda: protocol, sys.stdin)
    return stream_reader

Creates a reusable asynchronous standard-input reader by pairing StreamReaderProtocol with connect_read_pipe and sys.stdin. section 8.4

How Python Concurrency with asyncio covers it

How deep it goes
Explains construction, delegation, and pipe integration without descending into protocol internals.
Examples
Uses create_stdin_reader to connect sys.stdin and consume lines asynchronously with StreamReader.readline().
What it assumes
Assumes familiarity with asyncio streams, protocols, coroutines, and file-like objects such as sys.stdin.
What you can do after
Operate an asynchronous standard-input reader by pairing StreamReaderProtocol with connect_read_pipe.
How it connects
Ties StreamReaderProtocol to StreamReader, connect_read_pipe, ReadTransport, sys.stdin, and the event loop.

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.