On this page
subprocess
Prev: struct | Up: stdlib_module | Next: symtable
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — subprocess
Tags: #public #python3 #stdlib
Import
import subprocess
Overview
Spawns external OS processes, connects to their stdin/stdout/stderr streams, enforces timeouts, and checks exit codes. Reach for subprocess.run() for 95% of use cases; drop down to subprocess.Popen only when you need incremental streaming or bidirectional IPC with a long-running child process.
Quick Start
import subprocess
result = subprocess.run(
["python3", "-c", "print('hello')"],
capture_output=True,
text=True,
check=True,
timeout=10,
)
assert result.stdout.strip() == "hello"
Implementation Walkthrough
1. Running a Command Safely with Timeout & Error Reporting
Pass arguments as a list[str] (never shell=True with user input) and set check=True + timeout:
import subprocess
def git_head_sha(repo_dir: str) -> str:
try:
proc = subprocess.run(
["git", "-C", repo_dir, "rev-parse", "--short", "HEAD"],
capture_output=True,
text=True,
check=True,
timeout=5,
)
return proc.stdout.strip()
except subprocess.CalledProcessError as exc:
raise RuntimeError(f"git failed ({exc.returncode}): {exc.stderr.strip()}") from exc
except subprocess.TimeoutExpired as exc:
raise TimeoutError("git rev-parse timed out") from exc
2. Streaming Line-by-Line Output with Popen
import subprocess
with subprocess.Popen(
["python3", "-c", "for i in range(3): print(i)"],
stdout=subprocess.PIPE,
text=True,
) as proc:
assert proc.stdout is not None
lines = [line.strip() for line in proc.stdout]
assert proc.wait() == 0
Gotchas & Boundaries
- Avoid
shell=True: Passing an argument list bypasses the shell and eliminates command-injection bugs and quoting headaches. - Never use
Popen.stdout.read()withstderr=PIPEwithoutcommunicate(): Full OS pipe buffers will deadlock the child process; usesubprocess.run(..., capture_output=True)orproc.communicate(). - Always pass
timeout=: External binaries can hang indefinitely waiting for stdin or network I/O. - Use
sys.executableto invoke Python: Don't hardcode"python"or"python3"when spawning a subprocess in the same virtualenv.
Common Functions
- subprocess.call() —
call(*popenargs, timeout=None, **kwargs)— Run command with arguments. Wait for command to complete or for timeout seconds, then return the returncode attribute. - subprocess.check_call() —
check_call(*popenargs, **kwargs)— Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the - subprocess.check_output() —
check_output(*popenargs, timeout=None, **kwargs)— Run command with arguments and return its output. - subprocess.getoutput() —
getoutput(cmd, *, encoding=None, errors=None)— Return output (stdout or stderr) of executing cmd in a shell. - subprocess.getstatusoutput() —
getstatusoutput(cmd, *, encoding=None, errors=None)— Execute the string 'cmd' in a shell with 'check_output' and return a 2-tuple (status, output). The locale encoding is used to decode the output and process newlines. - subprocess.run() —
run(*popenargs, input=None, capture_output=False, timeout=None, check=False, **kwargs)— Run command with arguments and return a CompletedProcess instance.
Classes & Objects
- subprocess.CalledProcessError — Raised when run() is called with check=True and the process returns a non-zero exit status. (Methods:
.add_note(),.stdout(),.with_traceback()) - subprocess.CompletedProcess — A process that has finished running. (Methods:
.check_returncode()) - subprocess.Popen — Execute a child program in a new process. (Methods:
.communicate(),.kill(),.poll(),.send_signal(),.terminate(),.universal_newlines()) - subprocess.SubprocessError —
subprocess.SubprocessErrorclass. (Methods:.add_note(),.with_traceback()) - subprocess.TimeoutExpired — This exception is raised when the timeout expires while waiting for a child process. (Methods:
.add_note(),.stdout(),.with_traceback())
Constants & Attributes
subprocess.DEVNULL(int) =-3subprocess.PIPE(int) =-1subprocess.STDOUT(int) =-2
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/os
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/struct
- tuts/python3/stdlib_module/subprocess/call
- tuts/python3/stdlib_module/subprocess/CalledProcessError
- tuts/python3/stdlib_module/subprocess/check_call
- tuts/python3/stdlib_module/subprocess/check_output
- tuts/python3/stdlib_module/subprocess/CompletedProcess
- tuts/python3/stdlib_module/subprocess/getoutput
- tuts/python3/stdlib_module/subprocess/getstatusoutput
- tuts/python3/stdlib_module/subprocess/Popen
- tuts/python3/stdlib_module/subprocess/run
- tuts/python3/stdlib_module/subprocess/SubprocessError
- tuts/python3/stdlib_module/subprocess/TimeoutExpired
- tuts/python3/stdlib_module/symtable
- tuts/python3/tutorials/popular_application_domains
- tuts/python3/tutorials/popular_application_domains/automation_devops_and_web_scraping
Related notes
- tuts/python3/stdlib_module/os Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/struct Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/subprocess/call Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/subprocess/CalledProcessError Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/subprocess/check_call Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/subprocess/check_output Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/subprocess/CompletedProcess Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/subprocess/getoutput Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/subprocess/getstatusoutput Linked here; links to this page; shared tags: #stdlib