Sub topic 7
Stopping commands that run too long
This chapter assumes you can call subprocess.run, capture output, and handle exceptions such as CalledProcessError. It covers how to bound a command's run time, what the library does when the limit passes, and where that behavior stops short.
Why a time limit matters
By default, subprocess.run waits as long as the child process runs. If the child waits for a network host that never answers, or for input that never arrives, your program waits too. A script that runs unattended, such as a build step, a scheduled job, or a web request handler, needs a time limit so one stuck command cannot block everything else.
The timeout argument sets that limit. It is a number of seconds (an int or float). The default is None, which means no limit.
The timeout argument of run
import subprocess
import sys
try:
subprocess.run(
[sys.executable, "-c", "import time; time.sleep(10)"],
timeout=1,
)
except subprocess.TimeoutExpired as exc:
print("timed out after", exc.timeout, "seconds")When one second passes, run does three things:
- It kills the child process.
- It waits for the child to be reaped, so no zombie is left behind.
- It raises
subprocess.TimeoutExpired.
The timeout covers the whole life of the command, from the moment run starts waiting. It is not a limit on idle time. A child that prints a line every half second still gets killed at the limit.
What TimeoutExpired carries
The exception has these attributes:
| Attribute | Meaning |
|---|---|
| `cmd` | The command that was run |
| `timeout` | The limit in seconds |
| `stdout` (also `output`) | Output captured before the kill, or `None` |
| `stderr` | Error output captured before the kill, or `None` |
Partial output is useful for diagnosis, such as seeing where a build hung. One quirk applies. Even when you pass text=True, the captured partial output on the exception is often bytes. Decode it defensively:
import subprocess
import sys
code = "import time; print('started', flush=True); time.sleep(10)"
try:
subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
text=True,
timeout=2,
)
except subprocess.TimeoutExpired as exc:
partial = exc.stdout or b""
if isinstance(partial, bytes):
partial = partial.decode(errors="replace")
print("partial output:", partial.strip())The flush=True matters. A child writing to a pipe usually buffers its output, so text it has "printed" may still sit inside the child when it is killed. Flushed text can be read before the kill. Buffered text is lost.
Timeout and check=True together
A timeout and check=True do not conflict. A command killed by timeout never produces a normal return code, so you get TimeoutExpired, not CalledProcessError. Catch both when you want to treat them differently:
import subprocess
import sys
def run_limited(cmd, seconds):
try:
return subprocess.run(cmd, capture_output=True, text=True,
check=True, timeout=seconds)
except subprocess.TimeoutExpired:
print("too slow:", cmd)
except subprocess.CalledProcessError as exc:
print("failed with code", exc.returncode)
return None
run_limited([sys.executable, "-c", "import time; time.sleep(5)"], 1)
run_limited([sys.executable, "-c", "import sys; sys.exit(2)"], 5)The timeout does not apply to starting the program. If the executable does not exist, you still get FileNotFoundError at once.
Which APIs kill the child
run kills the child for you. The lower-level methods do not.
| Call | On timeout |
|---|---|
| `subprocess.run(..., timeout=)` | Kills the child, raises `TimeoutExpired` |
| `subprocess.check_output(..., timeout=)` | Same as `run` |
| `Popen.wait(timeout=)` | Raises `TimeoutExpired`, child keeps running |
| `Popen.communicate(timeout=)` | Raises `TimeoutExpired`, child keeps running |
The Popen methods only stop your waiting. If you catch the exception and do nothing else, the child continues in the background. You must stop it yourself.
Asking politely first: terminate, then kill
run goes straight to kill(). On POSIX systems (Linux and macOS) that sends SIGKILL, which the child cannot catch. It gets no chance to remove temporary files, flush buffers, or stop its own helpers. If you want a gentler stop, use Popen and escalate in two steps:
terminate()sendsSIGTERMon POSIX, which a well-behaved program handles by cleaning up and exiting.kill()sendsSIGKILL, which cannot be ignored.
On Windows, both methods call TerminateProcess, so they behave the same.
import subprocess
import sys
def run_with_grace(cmd, timeout, grace=2.0):
with subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
) as proc:
try:
out, err = proc.communicate(timeout=timeout)
except subprocess.TimeoutExpired:
proc.terminate()
try:
out, err = proc.communicate(timeout=grace)
except subprocess.TimeoutExpired:
proc.kill()
out, err = proc.communicate()
raise subprocess.TimeoutExpired(
cmd, timeout, output=out, stderr=err
)
return subprocess.CompletedProcess(cmd, proc.returncode, out, err)
stubborn = "import signal, time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(30)"
try:
run_with_grace([sys.executable, "-c", stubborn], timeout=1, grace=1)
except subprocess.TimeoutExpired as exc:
print("gave up after", exc.timeout, "seconds")The child in this demo ignores SIGTERM, so the helper waits one grace second and then falls back to kill(). The with block waits for the child on exit, so the function never leaves a zombie behind.
The grandchild problem
kill() targets one process: the one Popen started. If that process started its own children, they survive. This is common with shell=True, where the child is the shell and your real command is the shell's child.
The trouble goes beyond leftover processes. Suppose you use capture_output=True. The surviving grandchild still holds the write end of the output pipe. After the kill, run reads from the pipe until end of input, and that end never arrives while the grandchild lives. Your "timed out" call can hang long after the deadline.
The remedy on POSIX is to put the child in its own process group and kill the whole group:
import os
import signal
import subprocess
if os.name == "posix":
with subprocess.Popen(
["sh", "-c", "sleep 30 & sleep 30"],
start_new_session=True,
) as proc:
try:
proc.wait(timeout=1)
except subprocess.TimeoutExpired:
os.killpg(proc.pid, signal.SIGKILL)
proc.wait()
print("exit code", proc.returncode)start_new_session=True makes the child the leader of a new session and process group, so its process group ID equals proc.pid. os.killpg then signals the shell and both sleep commands. On Windows, os.killpg does not exist. A common approach there is to run taskkill /T /F /PID <pid> through subprocess.run, where /T also ends the child's descendants.
Choosing a value
- Pick a limit from the command's normal time. Two to ten times the usual duration absorbs a slow disk or a busy machine without waiting forever.
- Tests that call external tools should always set a timeout. A hung subprocess otherwise hangs the whole test run.
- A timeout is not a retry policy. Decide separately whether a timed-out command is safe to run again. It may have done half its work.
- For many commands at once, the limit applies to each
runcall separately, so the total time is the sum unless you run them concurrently.
Common errors
- Catching
TimeoutExpiredfromcommunicate()and moving on withoutkill(). The child keeps running. - Treating
exc.stdoutasstr. It is oftenbytes, and it may beNone. - Using
timeout=0and expecting "no limit". Zero means "expire immediately". UseNonefor no limit. - Relying on
shell=Trueplus a timeout, then finding stray processes after the kill.
Exercise
A script calls subprocess.run("build.sh | tee log.txt", shell=True, capture_output=True, timeout=60). The build hangs, and the call does not return until several minutes after the 60 seconds pass. Why does this happen, and how would you change the code so the call ends near the deadline?
Show answer
With shell=True, run kills only the shell. The build and tee are the shell's children, so they survive and keep the captured output pipe open. After the kill, run waits for end of input on that pipe, which does not come until those processes exit. To fix it, avoid the shell and run the build with an argument list, writing the log from Python. If a shell is required, start it with Popen(..., start_new_session=True), use communicate(timeout=60), and on TimeoutExpired call os.killpg(proc.pid, signal.SIGKILL) followed by proc.communicate() (POSIX only).