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
