Sub topic 16
A short look at asyncio subprocesses
This chapter assumes you know subprocess.run and Popen from earlier chapters, and that you have basic familiarity with async and await. If you have not used asyncio before, treat this chapter as a preview.
Why asyncio has its own subprocess API
subprocess.run blocks the calling thread until the child exits. In an asyncio program, a blocked thread freezes the whole event loop. Every other task stops until the command finishes.
The asyncio module provides its own functions for starting child processes. They return awaitable objects, so the event loop can run other tasks while the child works.
Running one command
asyncio.create_subprocess_exec takes the program and its arguments as separate values, like a list passed to subprocess.run. It returns a Process object. Its communicate() method is a coroutine, so you await it.
import asyncio
import sys
async def main():
proc = await asyncio.create_subprocess_exec(
sys.executable, "-c", "print('hello')",
stdout=asyncio.subprocess.PIPE,
)
stdout, _ = await proc.communicate()
print(stdout.decode().strip())
print(proc.returncode)
asyncio.run(main())Two differences from subprocess.run matter here:
- There is no
text=True. The output is bytes, so you decode it yourself. - There is no
check=True. You readproc.returncodeand decide what to do.
asyncio.create_subprocess_shell also exists. It carries the same injection risks as shell=True, so prefer create_subprocess_exec.
Running commands at the same time
The benefit of asyncio is concurrency. This example starts three child processes that each sleep for one second. Run one after another they would take about three seconds. Run together they take about one.
import asyncio
import sys
import time
async def run(code):
proc = await asyncio.create_subprocess_exec(
sys.executable, "-c", code,
stdout=asyncio.subprocess.PIPE,
)
stdout, _ = await proc.communicate()
return stdout.decode().strip()
async def main():
start = time.perf_counter()
code = "import time; time.sleep(1); print('done')"
results = await asyncio.gather(run(code), run(code), run(code))
print(results)
print(f"{time.perf_counter() - start:.1f} seconds")
asyncio.run(main())Timeouts
There is no timeout argument on communicate(). Wrap the call in asyncio.wait_for instead. On timeout, wait_for cancels the wait but does not stop the child. You must kill it yourself.
import asyncio
import sys
async def main():
proc = await asyncio.create_subprocess_exec(
sys.executable, "-c", "import time; time.sleep(10)",
)
try:
await asyncio.wait_for(proc.communicate(), timeout=1)
except asyncio.TimeoutError:
proc.kill()
await proc.wait()
print("killed after timeout")
asyncio.run(main())The call to await proc.wait() after kill() collects the exit status, so no zombie process is left behind.
Common errors
- Forgetting to await.
proc.communicate()withoutawaitreturns a coroutine and does nothing. - Using
subprocess.runinside a coroutine. It works, but it blocks the loop and removes the benefit of asyncio. - Reading
stdoutwithoutPIPE. If you do not passstdout=asyncio.subprocess.PIPE,proc.stdoutisNone. - Deadlocks. The pipe buffer problem from the earlier chapter applies here too. Use
communicate(), or readproc.stdoutas lines arrive.
Exercise
Exercise
Why does await asyncio.wait_for(proc.communicate(), timeout=1) not stop a child that runs for ten seconds, and what must you add in the except asyncio.TimeoutError block?
Show answer
wait_for only cancels the waiting coroutine. The child process keeps running. You must call proc.kill() (or proc.terminate()) and then await proc.wait() to stop it and collect its exit status.
Exercise
You run asyncio.gather on four commands that each take two seconds. About how long should the total take, and why?
Show answer
About two seconds. The event loop waits on all four child processes at once, so their run times overlap instead of adding up.