Python asyncio Streams and Subprocesses/Run a subprocess with exec

Capture stdout and stderr asynchronously.

Section: Subprocesses

Run a subprocess with exec

python
python
import asyncio

async def main():
    proc = await asyncio.create_subprocess_exec(
        "python",
        "-c",
        "print('hello from child')",
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )
    stdout, stderr = await proc.communicate()
    print(stdout.decode().strip(), proc.returncode)

asyncio.run(main())
Explanation

Use `create_subprocess_exec()` when you want argument-safe subprocess calls.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Subprocesses
Run a shell command asynchronously
Spawn a shell pipeline with `create_subprocess_shell()`.
OpenIn sheetpythonsame section
Open a TCP connection
Use stream reader and writer objects.
Run blocking I/O in a thread
Use `asyncio.to_thread()` for simple thread offloading.
Start a TCP server
Serve client connections with async handlers.
Use `run_in_executor()`
Offload work with explicit loop executor integration.