subprocess.TimeoutExpired
PythonERRORNotableRuntime ErrorHIGH confidence
Subprocess timed out
Production Risk
Always kill subprocess on timeout and collect output to avoid orphan processes.
What this means
Raised by subprocess.run() or subprocess.communicate() when the child process does not finish within the specified timeout.
Why it happens
- 1External command takes longer than expected
- 2Command hangs waiting for input
- 3Network operation in subprocess stalls
How to reproduce
Running a slow command with a timeout.
trigger — this will error
trigger — this will error
import subprocess subprocess.run(['sleep', '30'], timeout=5)
expected output
subprocess.TimeoutExpired: Command '['sleep', '30']' timed out after 5 seconds
Fix
Kill the process after timeout
WHEN Handling TimeoutExpired
Kill the process after timeout
import subprocess
proc = subprocess.Popen(['slow_command'])
try:
stdout, stderr = proc.communicate(timeout=30)
except subprocess.TimeoutExpired:
proc.kill()
stdout, stderr = proc.communicate() # collect remaining output
print("Command timed out and was killed")Why this works
proc.kill() sends SIGKILL; calling communicate() after ensures the process is fully reaped.
Code examples
Triggerpython
import subprocess subprocess.run(["sleep", "30"], timeout=5) # TimeoutExpired after 5 seconds
Handle with killpython
import subprocess
proc = subprocess.Popen(["slow_cmd"])
try:
out, _ = proc.communicate(timeout=30)
except subprocess.TimeoutExpired:
proc.kill()
proc.communicate()Avoid with reasonable timeoutpython
import subprocess
result = subprocess.run(
cmd,
timeout=60,
capture_output=True
)
# Always set a timeout — never leave unboundedWhat not to do
✕ Ignore TimeoutExpired and let the process continue running
The process becomes a zombie/orphan consuming resources; always kill it on timeout.
Same error in other languages
Sources
Official documentation ↗
Python Docs — subprocess module
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev