liveBook · Manning

Asyncio.wait

As explained in Python Concurrency with asyncio

asyncio process.wait is a coroutine method that waits for the represented subprocess to terminate and returns its status code.

The Process.wait coroutine pauses until an asyncio-created subprocess terminates, then returns its status code. Create the process first with asyncio.create_subprocess_exec or asyncio.create_subprocess_shell; prefer the exec form unless shell functionality is required. section 13.1

Wait for a command to finish

Create a subprocess for ls -l, print its process ID, await process.wait(), and print the resulting status code. A successful run returns 0.

To impose a deadline, await asyncio.wait_for(process.wait(), timeout=1.0). A timeout does not terminate the subprocess automatically; catch asyncio.TimeoutError, call process.terminate(), and await process.wait() again to observe the final status.

Be careful when piping stdout or stderr. Waiting without consuming substantial subprocess output can deadlock when the stream buffer fills. Read the stream concurrently or use process.communicate() when the interaction is simple. section 13.1.1

Listing 13.1 Running a simple command in a subprocess
import asyncio
from asyncio.subprocess import Process
 
 
async def main():
    process: Process = await asyncio.create_subprocess_exec('ls', '-l')
    print(f'Process pid is: {process.pid}')
    status_code = await process.wait()
    print(f'Status code: {status_code}')
 
 
asyncio.run(main())

Shows the smallest complete pattern: create a subprocess, await its completion, and inspect the status code. section 13.1

How Python Concurrency with asyncio covers it

How deep it goes
Explains completion, timeout-driven termination, and pipe deadlocks without descending into subprocess implementation internals.
Examples
Uses ls -l, a delayed sleep process, piped ls output, and a high-volume output program to demonstrate completion and failure modes.
What it assumes
Requires creating an asyncio Process and understanding coroutines; introduces status inspection, termination, and subprocess stream coordination.
What you can do after
Operate subprocesses, enforce completion deadlines, terminate slow processes, and avoid output-buffer deadlocks.
How it connects
Connects subprocess creation with create_subprocess_exec, timeout control with wait_for, and I/O handling with communicate and stream readers.

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.