StreamReader in Python's asyncio

The StreamReader class in Python's asyncio module is a powerful tool for handling data streams. It provides methods such as readline and read to efficiently manage incoming data. This class is particularly useful in scenarios where asynchronous data reading is required, such as network communication or subprocess management.

Using StreamReader for HTTP Requests

One common use case for StreamReader is reading data from a network connection. The following example demonstrates how to perform an HTTP request using stream readers and writers:

Listing 8.3 A HTTP request with stream readers and writers

import asyncio
from asyncio import StreamReader
from typing import AsyncGenerator
 
 
async def read_until_empty(stream_reader: StreamReader) -> AsyncGenerator[str, None]:
    while response := await stream_reader.readline():                                                  #1
        yield response.decode()
 
 
async def main():
    host: str = 'www.example.com'
    request: str = f"GET / HTTP/1.1\r\n" \
                   f"Connection: close\r\n" \
                   f"Host: {host}\r\n\r\n"
 
    stream_reader, stream_writer = await asyncio.open_connection('www.example.com', 80)
 
    try:
        stream_writer.write(request.encode())                                                          #2
        await stream_writer.drain()
 
        responses = [response async for response in read_until_empty(stream_reader)]                   #3
 
        print(''.join(responses))
    finally:
        stream_writer.close()                                                                          #4
        await stream_writer.wait_closed()
 
 
asyncio.run(main())

In this example, we define an asynchronous generator read_until_empty that reads lines from a StreamReader and decodes them into strings. The main coroutine opens a connection to example.com, writes an HTTP request, and uses the generator to read the response. The StreamWriter is closed properly by calling close and awaiting wait_closed to ensure the connection is fully closed.

Decoupling Output Reading from Input Writing

StreamReader can also be used in subprocess management, where it is crucial to handle standard input and output concurrently. The following example demonstrates how to decouple reading from writing using StreamReader and StreamWriter:

Listing 13.14 Decoupling output reading from input writing

import asyncio
from asyncio import StreamWriter, StreamReader, Event
from asyncio.subprocess import Process
 
 
async def output_consumer(input_ready_event: Event, stdout: StreamReader):
    while (data := await stdout.read(1024)) != b'':
        print(data)
        if data.decode().endswith("Enter text to echo: "):
            input_ready_event.set()
async def input_writer(text_data, input_ready_event: Event, stdin: StreamWriter):
    for text in text_data:
        await input_ready_event.wait()
        stdin.write(text.encode())
        await stdin.drain()
        input_ready_event.clear()
 
async def main():
    program = ['python3', 'interactive_echo_random.py']
    process: Process = await asyncio.create_subprocess_exec(*program,
                                                            stdout=asyncio
                                                            .subprocess.PIPE,
                                                            stdin=asyncio
                                                            .subprocess.PIPE)
 
    input_ready_event = asyncio.Event()
 
    text_input = ['one\n', 'two\n', 'three\n', 'four\n', 'quit\n']
 
    await asyncio.gather(output_consumer(input_ready_event, process.stdout),
                         input_writer(text_input, input_ready_event,
                         process.stdin),
                         process.wait())
 
 
asyncio.run(main())

In this example, the output_consumer coroutine reads from the standard output using a StreamReader and sets an event when the input prompt is detected. The input_writer coroutine waits for this event before writing to the standard input using a StreamWriter. This separation of concerns allows for efficient and concurrent handling of input and output streams in subprocesses.

FAQ (Frequently asked questions)

What is the StreamReader class in asyncio used for?