Sub topic 11
Going lower level with Popen
This chapter assumes you know subprocess.run, its capture_output, text and check arguments, and how exit codes work. subprocess.run covers most jobs. Popen is the class underneath it, and it is the right tool when you need control while the child is still running.
What Popen does differently
subprocess.run starts a process, waits for it, and returns a CompletedProcess. Popen only starts the process and returns a Popen object right away. Your program keeps running while the child runs. Calling subprocess.Popen(...) accepts the same arguments as run, such as stdout=subprocess.PIPE, text=True, env and cwd.
The object has these members:
| Member | Meaning |
|---|---|
| `proc.pid` | The operating system's process ID. |
| `proc.poll()` | Returns the exit code if the child has finished, otherwise `None`. It never blocks. |
| `proc.wait(timeout=None)` | Blocks until the child exits and returns the exit code. |
| `proc.communicate(input=None, timeout=None)` | Sends input, reads all output, waits for exit, and returns `(stdout, stderr)`. |
| `proc.returncode` | `None` until the child has been reaped by `poll`, `wait` or `communicate`. |
| `proc.kill()` and `proc.terminate()` | Stop the child. |
communicate: the safe default
communicate is the method to reach for first. It writes any input, reads stdout and stderr until both close, and then waits for the process.
import subprocess
import sys
code = "import sys; print('data'); print('warning', file=sys.stderr)"
proc = subprocess.Popen(
[sys.executable, "-c", code],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
out, err = proc.communicate()
print("stdout:", out.strip())
print("stderr:", err.strip())
print("exit code:", proc.returncode)Call communicate only once per process. It reads everything into memory, so it suits output of modest size.
poll and wait
Use poll when you want to do other work while the child runs. Use wait when you only need to block until it exits.
import subprocess
import sys
import time
proc = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(1)"])
print("started, poll gives", proc.poll())
while proc.poll() is None:
print("still working...")
time.sleep(0.3)
print("finished with", proc.returncode)Timeouts need cleanup
Unlike run, Popen does not kill the child when a timeout passes. communicate(timeout=...) and wait(timeout=...) raise TimeoutExpired and leave the process running. You must stop it yourself, then collect its output.
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("killed, exit code", proc.returncode)The second communicate call after kill is the documented way to finish cleanly. It reaps the process, so no zombie is left behind.
Use a with block
Popen works as a context manager. Leaving the with block closes the pipes and waits for the child to exit.
import subprocess
import sys
with subprocess.Popen([sys.executable, "-c", "print('done')"]) as proc:
pass
print(proc.returncode)Common mistakes
- Reading
returncodebefore callingpoll,waitorcommunicate. It is stillNone. - Setting
stdout=subprocess.PIPEand never reading it. A chatty child can fill the pipe buffer and hang. A later chapter covers this. - Forgetting that
Popennever raises on a non-zero exit. You must checkreturncodeyourself. - Forgetting to kill the child after
TimeoutExpired.
Exercise
A program calls proc.communicate(timeout=2) on a Popen object and catches TimeoutExpired, but the child keeps running afterward. What two calls should the except block make, and in what order?
Show answer
Call proc.kill() first to stop the child, then call proc.communicate() again to collect the remaining output and reap the process. Popen does not kill the child on timeout the way subprocess.run does.