Sub topic 7
Stopping commands that run too long
This chapter assumes you can already call subprocess.run, capture output, and handle exceptions. A child process can hang, for example when it waits on a network call or for input that never arrives. Without a limit, your program hangs with it. The timeout argument gives you that limit.
Setting a timeout
Pass timeout as a number of seconds. If the child is still running when the time is up, run kills it and raises subprocess.TimeoutExpired.
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")
print("command was", exc.cmd)The exception carries these attributes:
cmd: the command that was run.timeout: the limit you set.stdoutandstderr: any output collected before the kill, orNoneif you did not capture output.
What happens inside run
The timeout is a deadline for the whole call. It is not a limit on idle time or on any single read. When the deadline passes, run kills the child, waits for it to exit, and re-raises the exception. You do not need to clean up the child yourself.
Reading partial output
If you captured output, the exception may hold what the child wrote before it was killed. Do not assume it is text. Even with text=True, exc.stdout can be bytes, so decode it when you need to print it.
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=1,
)
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 that writes to a pipe usually buffers its output, so text still sitting in its buffer is lost when it is killed.
Common errors
- Forgetting to catch the exception.
TimeoutExpiredis not a subclass ofCalledProcessError. Anexcept CalledProcessErrorblock will not catch it, so handle both separately. - Using
shell=Truewith a timeout. The kill goes to the shell, not to the programs the shell started. Those grandchildren can keep running, and they can keep the output pipes open sorunstays blocked. Pass an argument list instead, so the process you start is the one that gets killed. - Expecting a limit on the child's own children. If the program you run starts workers, killing it does not necessarily stop them. Use the program's own options to control them, or manage the process group yourself.
- Setting
timeout=0or a negative value. It does not mean "no limit". UseNone, the default, for that. - Treating a timeout as a normal failure. A killed child has no useful exit status. Decide in your code whether to retry, log, or give up.
Retrying with a longer limit
A common pattern is to catch the exception and try again with a larger limit:
import subprocess
import sys
def run_with_retry(cmd, limits):
for limit in limits:
try:
return subprocess.run(cmd, capture_output=True, text=True, timeout=limit)
except subprocess.TimeoutExpired:
print(f"no result within {limit}s")
return None
result = run_with_retry([sys.executable, "-c", "print('done')"], [1, 2])
print(result.stdout.strip() if result else "gave up")Exercise
A program runs subprocess.run("sleep 30", shell=True, timeout=2) and sometimes stays blocked far longer than 2 seconds when output is captured. Why can this happen, and what is the first change you would make?
Show answer
With shell=True the timeout kills the shell, but the program the shell started can survive and keep the output pipes open, so run keeps waiting. Pass an argument list, such as ["sleep", "30"], so the process that gets killed is the one doing the work.