Use this when Python runs external commands.
subprocess
subprocess runs external commands from Python, such as subprocess.run(['ping', '-c', '1', host], capture_output=True, check=True). Pass arguments as a list and avoid shell=True with untrusted input.
1. subprocess.run with argument lists, check=True, capture_output, timeout.
2. Avoid shell=True.
3. Handle CalledProcessError.
4. Log commands.
5. Prefer native libraries when available.
args list → subprocess → exit code/output
Context & applicabilityCommon mistakes · platform/version boundaries
Operational reference
Fast context before you go deeper.
Verification & Troubleshooting
Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.
Use the operational verification above to establish the expected state.
Capture the concrete output, symptom, packet, log or counter before changing anything.
Step 1 Verification path Verify boundary
The negative fixture should deliberately exercise risks such as environment drift, implicit coercion, broad exception handling, blocking/async confusion, shell quoting/subprocess risks, partial writes and non-deterministic external APIs, choosing the cases most relevant to argument-vector versus shell invocation, stdin/stdout/stderr capture, timeout/cancellation, return codes and avoiding command-injection/quoting ambiguity.
Step 2 Common mistakes Narrow the fault
shell=Truewith user input.
Step 3 Where it fails Narrow the fault
Common failure classes include environment drift, implicit coercion, broad exception handling, blocking/async confusion, shell quoting/subprocess risks, partial writes and non-deterministic external APIs.
Evidence · 1 on this Topic
Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.
- Use subprocess.run with a list of arguments.
- check=True raises on non-zero exit.
- Avoid shell=True with untrusted input.
python3 -c "import subprocess;print(subprocess.run(['echo','ok'],capture_output=True,text=True,check=True).stdout)"— safe call- No shell=True with user input — injection
- timeout= set — hangs
ReferenceWhy it matters1 section · depth on demand
In depth
The subprocess module runs external commands from Python — useful when a CLI tool does something no library offers. Using it safely means passing arguments as a list (no shell), checking the exit code and setting a timeout.
import subprocess
res = subprocess.run(
["ping", "-c", "3", host],
capture_output=True, text=True, timeout=15, check=False,
)
if res.returncode != 0:
log.warning("%s unreachable: %s", host, res.stderr.strip())
Avoid shell=True with any user or external input — it allows command injection. Use check=True to raise on failure when a non-zero exit should stop the script, and prefer tools' JSON output options when parsing results.
ReferenceImportant terms & boundaries1 section · depth on demand
Mechanics
The linked authority for bounded mechanics is Python Documentation — subprocess; documentation support is separate from observed lab/production Evidence.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Verification history & basis
When and against what this Topic was checked. Later text edits do not count as a new check.
Authoritative/upstream documentation reviewed for bounded claims in Python Automation > subprocess. Documentation verification only; this is not observed lab or production Evidence.
Basis: https://docs.python.org/3/library/subprocess.html · confidence 94%Deep reference
Healthy vs suspicious evidence
Output interpretation
For argument-vector versus shell invocation, stdin/stdout/stderr capture, timeout/cancellation, return codes and avoiding command-injection/quoting ambiguity, prefer typed fields and stable IDs over human presentation text.