Python 3.3+Exceptionsexception
subprocess.TimeoutExpired
module exceptions
Raised when a child process does not finish within the timeout given to run, call, check_output or Popen.wait/communicate.
Syntax
except subprocess.TimeoutExpired as e: # e.cmd, e.timeout, e.output, e.stderr
run() kills the child before raising it, but Popen.wait(timeout) and communicate(timeout) do not: the process keeps running, and you must call proc.kill() and then communicate() to reap it. The output/stderr attributes hold bytes even with text=True. It is not a subclass of the built-in TimeoutError, so except TimeoutError lets it through.
Examples
import subprocess, sys
cmd = [sys.executable, '-c', 'import time; time.sleep(5)']
try:
subprocess.run(cmd, timeout=0.5)
except subprocess.TimeoutExpired as e:
print(round(e.timeout, 1)) # → 0.5 — до 3.13 здесь лежало прошедшее время
print(issubclass(subprocess.TimeoutExpired, TimeoutError)) # → False
import subprocess, sys
p = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(5)'])
try:
p.wait(timeout=0.3)
except subprocess.TimeoutExpired:
print(p.poll()) # → None — процесс ещё жив
p.kill()
p.wait()
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy