Standard input is a process’s conventional text input stream, commonly connected to a terminal or redirected from another source. In asynchronous Python, ordinary input() blocks the entire thread, preventing background tasks from completing. section 8.4
Use standard input differently depending on the surrounding application:
- Read directly with input() for simple synchronous command-line programs. section 8.4
- Adapt sys.stdin to an asyncio StreamReader through connect_read_pipe and StreamReaderProtocol, then await readline(). section 8.4
- Give an asynchronously created subprocess a PIPE for standard input, then write through its StreamWriter and await drain(). section 13.2
Asynchronous console input
Create a StreamReader, connect it to sys.stdin with StreamReaderProtocol, and await stdin_reader.readline() while delay tasks continue running. This allows input-driven work and background tasks to proceed concurrently. 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
Shows the helper that connects sys.stdin to an asyncio StreamReader. section 8.4




