Sub topic 11
Going lower level with Popen
This chapter assumes you can use subprocess.run, know what stdout, stderr and exit codes are, and understand the difference between text and bytes. subprocess.Popen is the class that run is built on. You need it when you must act while the child process is still running.
How run relates to Popen
subprocess.run creates a Popen object, calls communicate() on it, waits for the exit, and packages the results in a CompletedProcess. If a timeout fires, it kills the child. Popen gives you the object before any of that happens.
The key difference is timing. run blocks until the child exits. Popen(...) returns as soon as the operating system has started the child, and your program continues running next to it.
Here is how the two APIs differ:
| Feature | `subprocess.run` | `subprocess.Popen` |
|---|---|---|
| Waits for the child | Yes, always | Only when you ask |
| `capture_output=True` | Supported | Not available, use `stdout=PIPE` and `stderr=PIPE` |
| `check=True` | Supported | Not available, check `returncode` yourself |
| `input=` | A keyword of `run` | Passed to `communicate(input=...)` |
| Return value | `CompletedProcess` | A live process handle |
The arguments that describe the child are the same in both: the argument list, shell, cwd, env, stdin, stdout, stderr, text and encoding. Everything you learned about them still applies.
Starting a process and collecting its output
stdout=subprocess.PIPE tells Python to create a pipe between the child's standard output and your program. Without it, the child writes to the same terminal as your program, and proc.stdout is None.
import subprocess
import sys
proc = subprocess.Popen(
[sys.executable, "-c", "print('hello from child')"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
out, err = proc.communicate()
print(out.strip())
print(repr(err))
print(proc.returncode)This prints hello from child, then '', then 0. communicate() does three things in one call:
- It sends any
inputyou gave it to the child's standard input, then closes that pipe. - It reads standard output and standard error until both reach end of file.
- It waits for the child to exit and returns
(stdout, stderr).
If you did not request a pipe for a stream, the matching element of the returned tuple is None.
The process handle
A Popen object exposes a small set of attributes and methods.
proc.pidis the operating system's process ID.proc.returncodeisNonewhile the child is believed to be running. Once the exit has been observed, it holds the exit status.proc.poll()checks whether the child has finished, without blocking. It returnsNoneif the child is still running, otherwise the exit code. It also setsreturncode.proc.wait(timeout=None)blocks until the child exits and returns the exit code. With a timeout, it raisesTimeoutExpiredif the child is still running.proc.communicate(input=None, timeout=None)is described above.proc.terminate(),proc.kill()andproc.send_signal(sig)ask the child to stop.
The Reaped state matters on Linux and macOS. A finished child stays in the process table as a zombie until its parent collects the exit status. Calling poll(), wait() or communicate() does that. If you start many children and never do either, zombies accumulate. Python also emits a ResourceWarning when a Popen object is garbage collected while its child is still running.
Doing other work while the child runs
Use poll() when your program has something to do between checks.
import subprocess
import sys
import time
proc = subprocess.Popen(
[sys.executable, "-c", "import time; time.sleep(1.5)"]
)
while proc.poll() is None:
print("still running, pid", proc.pid)
time.sleep(0.5)
print("exit code", proc.returncode)This loop prints the "still running" line about three times, then exit code 0. A polling loop with sleep is fine for short jobs. For many children at once, or for events from a child's output, threads or asyncio fit better. The last chapter of this tutorial looks at asyncio.
Return codes and signals
Because Popen has no check=True, you test returncode yourself:
if proc.returncode != 0:
raise RuntimeError(f"child failed with {proc.returncode}")On Linux and macOS, a negative returncode means the child was ended by a signal. A value of -9 means signal 9 (SIGKILL), and -15 means SIGTERM. On Windows, terminate() and kill() are the same operation, and the exit code is simply a number the child process reports.
Stopping a child cleanly
terminate() sends SIGTERM on POSIX, which a well-written program treats as a request to shut down and clean up. kill() sends SIGKILL, which cannot be caught. The usual pattern is to ask politely, wait briefly, then force:
import subprocess
import sys
proc = subprocess.Popen(
[sys.executable, "-c", "import time; time.sleep(30)"]
)
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
print("returncode", proc.returncode)On Linux and macOS this prints returncode -15. On Windows it prints returncode 1. The final wait() after kill() is what reaps the child.
Timeouts with communicate
communicate(timeout=...) raises TimeoutExpired, but unlike run, it does not kill the child. That is your job. After you kill the child, call communicate() again to collect output that arrived before the kill and to finish cleanup.
import subprocess
import sys
proc = subprocess.Popen(
[sys.executable, "-c", "import time; time.sleep(10)"],
stdout=subprocess.PIPE,
text=True,
)
try:
out, _ = proc.communicate(timeout=1)
except subprocess.TimeoutExpired:
proc.kill()
out, _ = proc.communicate()
print("returncode", proc.returncode)
print(repr(out))This prints a non-zero returncode (-9 on POSIX) and an empty string, because the child printed nothing.
Using Popen as a context manager
Popen supports with. On exit from the block, Python closes the pipes and waits for the child to finish.
import subprocess
import sys
with subprocess.Popen(
[sys.executable, "-c", "print('done')"],
stdout=subprocess.PIPE,
text=True,
) as proc:
first_line = proc.stdout.readline()
print(first_line.strip(), proc.returncode)The context manager only waits. It does not kill a child that runs forever. If the body of the with block raises an exception, the exit still waits for the child, so a hung child makes the program hang. Combine it with try and kill() when the child might not stop on its own.
Gotchas
- Calling
wait()after requestingstdout=PIPEcan deadlock. If the child writes more than the operating system's pipe buffer holds (often 64 KiB on Linux), it blocks until someone reads. If you are sitting inwait(), nobody reads, and neither side makes progress. The python documentation warns about this. Usecommunicate()instead, or read the output as it arrives. A later chapter covers this in detail. communicate()holds all output in memory. For very large output, read the stream in chunks, or send it to a file withstdout=open(...).- Output is buffered inside the child. When a child's
stdoutis a pipe instead of a terminal, many programs switch to block buffering, so lines may arrive late and in bursts. A Python child can be run with-uto turn buffering off. stderr=subprocess.STDOUTmerges the error stream into the output stream.subprocess.DEVNULLdiscards a stream. Both are useful when you do not need to keep stderr separate.- With
text=True, the pipes are decoded using the locale's encoding. Passencoding="utf-8"explicitly when the child's encoding is known.
Exercise
A program starts proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) and then calls proc.wait() before reading proc.stdout. The command works fine when it prints a few lines, but hangs when it prints several megabytes. Why, and what is the simplest fix?
Show answer
The child fills the pipe buffer and blocks while writing, because the parent is waiting for it to exit and not reading. The parent waits for the child, and the child waits for the parent, so both stop. The simplest fix is to call out, _ = proc.communicate(), which reads the output while waiting for the exit. Alternatives are to read proc.stdout in a loop before waiting, or to redirect stdout to a file.
Exercise
You call proc.communicate(timeout=2) and it raises TimeoutExpired. What must you do next, and which call collects the remaining output?
Show answer
Stop the child yourself, for example with proc.kill(), because Popen does not kill it on timeout. Then call proc.communicate() again with no timeout. That call returns the output received so far, waits for the child to exit, and sets returncode.