Running Commands with subprocess
Automation scripts constantly call other programs: git, kubectl, terraform, systemctl, jq. Python's
subprocess.run does it safely if you follow a few rules: pass arguments as a list, check the exit status, capture
output as text, and set a timeout. This lesson shows each rule and what goes wrong without it.
The browser's Python cannot start processes, so every example here is a real session: a Python file run by
python3 3.12 in a Linux container.
The basic call
cat > run_basics.py <<'PY'
import subprocess
# Run, wait, and look at the result
r = subprocess.run(["git", "--version"], capture_output=True, text=True, check=True)
print("returncode:", r.returncode)
print("stdout:", r.stdout.strip())
# Output as data: let jq do the parsing
r = subprocess.run(["jq", "-r", ".items[].name"], input='{"items": [{"name": "api"}, {"name": "web"}]}',
capture_output=True, text=True, check=True)
print("names:", r.stdout.split())
# A failing command with check=True raises CalledProcessError
try:
subprocess.run(["ls", "/no/such/dir"], capture_output=True, text=True, check=True)
except subprocess.CalledProcessError as e:
print(f"failed: {e.cmd} exited {e.returncode}, stderr: {e.stderr.strip()}")
PY
python3 run_basics.pyreturncode: 0
stdout: git version 2.43.0
names: ['api', 'web']
failed: ['ls', '/no/such/dir'] exited 2, stderr: ls: cannot access '/no/such/dir': No such file or directory
| Argument | Why |
|---|---|
| a list of arguments | no shell is involved, so spaces, quotes and ; in values are just characters |
capture_output=True |
collect stdout and stderr instead of printing them |
text=True |
decode bytes to str (with the locale's encoding; add encoding="utf-8" to be explicit) |
check=True |
a non-zero exit status raises CalledProcessError, the equivalent of set -e |
input= |
send a string to the command's stdin |
Without check=True, a failed command is silently ignored unless you test r.returncode yourself, the same trap as
a Bash script without set -e.
Never build a shell command from input
shell=True passes one string to /bin/sh. Combined with a value from a user, a file or an API, it is a command
injection:
cat > injection.py <<'PY'
import subprocess
branch = "main; echo INJECTED: this could have been rm -rf" # e.g. from a webhook payload
print("--- shell=True with an f-string (vulnerable)")
subprocess.run(f"echo checking out {branch}", shell=True)
print("--- argument list (safe)")
subprocess.run(["echo", "checking out", branch])
print("--- when you really need a shell, quote every value")
import shlex
subprocess.run(f"echo checking out {shlex.quote(branch)} | tr a-z A-Z", shell=True)
PY
python3 injection.py--- shell=True with an f-string (vulnerable)
checking out main
INJECTED: this could have been rm -rf
--- argument list (safe)
checking out main; echo INJECTED: this could have been rm -rf
--- when you really need a shell, quote every value
CHECKING OUT MAIN; ECHO INJECTED: THIS COULD HAVE BEEN RM -RF
Use a list whenever you can. Pipes and redirections, the usual reason for reaching for shell=True, can be done in
Python instead: pass input= and read stdout, or connect two processes with stdin=p1.stdout. If you must use a
shell, quote every interpolated value with shlex.quote.
Timeouts, environment and working directory
cat > run_options.py <<'PY'
import os
import subprocess
# A hung command: kill it after 1 second
try:
subprocess.run(["sleep", "10"], timeout=1)
except subprocess.TimeoutExpired as e:
print(f"timed out: {e.cmd}")
# Extra environment variables: copy the current environment, then add
env = {**os.environ, "GIT_AUTHOR_NAME": "deploy-bot", "LC_ALL": "C"}
os.makedirs("repo", exist_ok=True)
subprocess.run(["git", "init", "-q"], cwd="repo", check=True)
r = subprocess.run(["git", "var", "GIT_AUTHOR_IDENT"], cwd="repo", env=env,
capture_output=True, text=True, check=True)
print("author:", r.stdout.rsplit(" ", 2)[0])
# Command not found is an exception too, not a return code
try:
subprocess.run(["kubectl", "version"], check=True)
except FileNotFoundError as e:
print("not installed:", e.filename)
PY
python3 run_options.pytimed out: ['sleep', '10']
author: deploy-bot <ada@example.com>
not installed: kubectl
timeout=kills the child and raisesTimeoutExpired. Every call to something that can hang (network tools,kubectl,ssh) deserves one.env=replaces the whole environment. Start fromos.environand add to it, or the child losesPATH,HOMEand the rest.cwd=runs the command in another directory withoutos.chdir(), which would change the directory for the rest of your program.- A missing program raises
FileNotFoundError(no shell, so there is no status 127).shutil.which("kubectl")checks in advance.
Streaming output from long commands
capture_output holds everything in memory until the command ends. For a long build or a terraform apply, read
the output line by line as it arrives, so logs appear in real time and you can react to them:
cat > stream.py <<'PY'
import subprocess
import sys
cmd = ["bash", "-c", "for i in 1 2 3; do echo step $i; sleep 0.1; done; echo 'warning: disk 91%' >&2; exit 3"]
with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1) as p:
for line in p.stdout:
tag = "WARN" if "warning" in line else " "
print(f"[{tag}] {line}", end="")
rc = p.wait()
print("exit status:", rc)
sys.exit(rc)
PY
python3 stream.py; echo "-> status $?"[ ] step 1
[ ] step 2
[ ] step 3
[WARN] warning: disk 91%
exit status: 3
-> status 3
stderr=subprocess.STDOUT merges the two streams in the order they were written, which is what you want for logs.
Passing the child's status on with sys.exit(rc) keeps your wrapper honest.
When to stop shelling out
Calling kubectl get pods -o json and parsing the output works, and it is often the quickest route. As a tool
grows, the official SDKs (the kubernetes Python client, boto3, google-cloud-*, azure-*) are faster, give you
typed errors instead of parsed stderr, and do not depend on a CLI version being installed. A good rule: shell out for
glue and one-offs, use the SDK for anything that loops over many objects or must handle errors precisely.
Test yourself
What does check=True do in subprocess.run?
- Checks the command exists before running it
- Raises CalledProcessError if the command exits with a non-zero status
- Captures output
- Runs the command through the shell
Why is subprocess.run(f"git checkout {branch}", shell=True) dangerous?
- git does not accept f-strings
- A value containing
;or$(…)is executed by the shell: command injection - shell=True is slower
- It cannot capture output
What happens if you pass env={"FOO": "1"} to subprocess.run?
- FOO is added to the current environment
- The child gets only FOO: PATH, HOME and everything else are gone
- It raises an error
- env is ignored without shell=True