Sub topic 16
A short look at asyncio subprocesses
This chapter assumes you know subprocess.run and Popen, including pipes, communicate, and why pipe buffers can deadlock. It also assumes you can read basic async and await code and know that asyncio.run starts an event loop. The chapter covers the asyncio versions of these tools, and where they differ from the ones you already know.
Why a second API exists
subprocess.run blocks the calling thread until the child exits. That is fine in a script. It is a problem inside an asyncio program, because a blocked thread freezes the whole event loop. While your code waits on a slow command, no other task runs: no network handlers, no timers, no other commands.
asyncio provides its own subprocess API. You start a child with await, and while the child runs, the event loop is free to run other tasks. The key functions are:
asyncio.create_subprocess_exec(program, *args, ...)starts a program from an argument list, likePopenwith a list.asyncio.create_subprocess_shell(command, ...)starts a command string through the shell, likeshell=True.
Both return an asyncio.subprocess.Process object. Its interface resembles Popen, but most of its methods are coroutines that you must await.
Running one command
The asyncio version of "run and capture" is create_subprocess_exec followed by communicate.
import asyncio
import sys
async def main():
proc = await asyncio.create_subprocess_exec(
sys.executable, "-c", "print('hello')",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await proc.communicate()
print(stdout.decode().strip())
print(proc.returncode)
asyncio.run(main())This prints hello and then 0. Compare it with subprocess.run:
| Feature | `subprocess.run` | asyncio subprocess |
|---|---|---|
| Blocks the thread | Yes | No, you `await` |
| Program and arguments | One list | Separate positional arguments |
| Text mode (`text=True`) | Supported | Not available, streams carry bytes |
| `check=True` | Supported | Not available, check `returncode` yourself |
| `timeout=` | Supported | Not available, use `asyncio.wait_for` |
| `capture_output=True` | Supported | Pass `stdout=PIPE` and `stderr=PIPE` explicitly |
| Return value | `CompletedProcess` | `Process`, with output returned by `communicate()` |
Three differences matter most in practice.
- Arguments are not a list. You write
create_subprocess_exec(sys.executable, "-c", code), notrun([sys.executable, "-c", code]). - Output is always bytes. Call
.decode()yourself, and pick the encoding explicitly if the child does not use UTF-8. - There is no
check=True. A non-zero exit is not an exception. Inspectproc.returncodeaftercommunicate()orwait().
The constants PIPE, STDOUT and DEVNULL live in asyncio.subprocess. They behave as they do in subprocess.
Handling failures
A failed launch still raises an exception. If the program does not exist, await asyncio.create_subprocess_exec(...) raises FileNotFoundError, exactly as Popen does. A program that starts and then fails only shows up as a non-zero returncode. A small helper restores the check=True behavior:
import asyncio
import subprocess
import sys
async def run_checked(*args):
proc = await asyncio.create_subprocess_exec(
*args,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await proc.communicate()
if proc.returncode != 0:
raise subprocess.CalledProcessError(
proc.returncode, args, output=stdout, stderr=stderr
)
return stdout.decode()
async def main():
try:
await run_checked(sys.executable, "-c", "import sys; sys.exit(3)")
except subprocess.CalledProcessError as exc:
print("command failed with code", exc.returncode)
asyncio.run(main())Reusing CalledProcessError means callers can catch the same exception type they already use with the blocking API.
Running commands concurrently
The reason to use this API is concurrency. With asyncio.gather, several children run at once, and total time is close to that of the slowest child.
import asyncio
import sys
import time
async def run_one(n, sem):
async with sem:
proc = await asyncio.create_subprocess_exec(
sys.executable, "-c",
f"import time; time.sleep(1); print({n} * {n})",
stdout=asyncio.subprocess.PIPE,
)
stdout, _ = await proc.communicate()
return n, proc.returncode, stdout.decode().strip()
async def main():
sem = asyncio.Semaphore(2)
start = time.perf_counter()
results = await asyncio.gather(*(run_one(n, sem) for n in range(4)))
for result in results:
print(result)
print(f"elapsed: {time.perf_counter() - start:.1f}s")
asyncio.run(main())Four one-second children finish in about two seconds, not four, because the semaphore allows two at a time. Without the semaphore all four would run together and finish in about one second.
The semaphore is not decoration. Every child is a real operating system process, and starting hundreds at once can exhaust process limits or file descriptors. Cap concurrency with a Semaphore whenever the number of commands is not small and fixed.
Streaming output
proc.stdout is an asyncio.StreamReader. You read from it with await proc.stdout.readline(), or loop over it with async for. This is the asyncio counterpart of iterating over Popen.stdout.
import asyncio
import sys
async def main():
proc = await asyncio.create_subprocess_exec(
sys.executable, "-u", "-c", "for i in range(3): print(i)",
stdout=asyncio.subprocess.PIPE,
)
async for line in proc.stdout:
print("got", line.decode().rstrip())
await proc.wait()
print("exit code", proc.returncode)
asyncio.run(main())Each line is a bytes object that includes the trailing newline. The -u flag makes the child Python process unbuffered, so lines arrive as they are printed. Without it, a child writing to a pipe usually buffers its output and sends it in large chunks.
Timeouts and cleanup
There is no timeout= argument. Wrap the awaited call in asyncio.wait_for instead, and clean up yourself.
import asyncio
import sys
async def main(timeout):
proc = await asyncio.create_subprocess_exec(
sys.executable, "-c", "import time; time.sleep(10)",
stdout=asyncio.subprocess.PIPE,
)
try:
await asyncio.wait_for(proc.communicate(), timeout)
except asyncio.TimeoutError:
proc.kill()
await proc.wait()
print("killed after", timeout, "seconds")
asyncio.run(main(1))wait_for cancels the awaited coroutine when the time runs out, but it does not stop the child. This differs from subprocess.run(timeout=...), which kills the child for you. After the timeout you must call proc.kill() (or proc.terminate() for a gentler signal) and then await proc.wait(). The final wait collects the exit status, so the child does not remain as a zombie process, and it lets asyncio release the process's transport cleanly.
On Python 3.11 and later, async with asyncio.timeout(seconds): is an alternative to wait_for. The cleanup rules are the same.
Shell commands and security
create_subprocess_shell(cmd) passes a string to the system shell. It has the same injection risk as shell=True: any untrusted text in cmd can add commands. Prefer create_subprocess_exec with separate arguments. If you must use the shell, quote each untrusted value with shlex.quote.
Platform and design notes
- Windows needs the Proactor event loop. It is the default since Python 3.8, so
asyncio.runworks. ASelectorEventLoop, which you can still select explicitly, raisesNotImplementedErrorwhen you try to start a subprocess. - Child exit detection varies by platform. On Unix, asyncio learns about exits through a child watcher mechanism. In current Python versions it is chosen automatically, and you rarely touch it. Code that creates its own event loops in worker threads on older Python versions deserves extra testing.
- Run it in an event loop.
create_subprocess_execcan only be awaited inside a running loop. In a plain script, wrap the code inasyncio.run. - A thread is a simpler alternative. If you only need to call one blocking
subprocess.runfrom async code,await asyncio.to_thread(subprocess.run, [...], capture_output=True, text=True, check=True)keepstext,checkandtimeoutworking and does not block the loop. Choose the native asyncio API when you need streaming, many concurrent children, or fine control over cancellation.
Exercise
You call await asyncio.wait_for(proc.communicate(), 5) and the child takes 20 seconds. The call raises TimeoutError. Is the child process still running at that point, and what two calls should you make in the except block?
Show answer
Yes, the child is still running. wait_for cancels only the awaiting coroutine, not the operating system process. In the except block call proc.kill() (or proc.terminate()) and then await proc.wait(), so the process is stopped and its exit status is collected.
Exercise
A coworker replaces subprocess.run(["tool"], capture_output=True, text=True, check=True) with an asyncio call that passes stdout=PIPE, stderr=PIPE to create_subprocess_exec("tool"). They then do print(stdout.upper()) and see the error "bytes object has no attribute ..." or garbled output, and a failing tool goes unnoticed. Name the two missing steps.
Show answer
First, decode the bytes with stdout.decode(), because asyncio streams have no text=True mode. Second, check proc.returncode after communicate() and raise an exception if it is non-zero, because there is no check=True.