Pcornel
Browse topics
Options
Recent
Favorites
Automation · Technical reference

subprocess

Direct answer

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.

When to use this

Use this when Python runs external commands.

First 30 seconds

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.

Operational verification

args list → subprocess → exit code/output

Context & applicabilityCommon mistakes · platform/version boundaries
Platform / version applicability
Python automation runtime
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

PlatformPython automation runtime · Automation implementations are tool and platform specific. Use the adjacent Domain for the technology being automated and this Domain for automation behavior.
Scope / prerequisiteUse this when Python runs external commands.
What next?3 suggested next steps
Evidence1
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

3 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

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=True with 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 references

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.

observation · 1
Key points
  • Use subprocess.run with a list of arguments.
  • check=True raises on non-zero exit.
  • Avoid shell=True with untrusted input.
Key checks
  • 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
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Technical verification history

Verification history & basis

When and against what this Topic was checked. Later text edits do not count as a new check.

2026-09-14 · vendor docPython automation runtime current

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%
Depth when you need it

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.

Confirmation

Confirm action

Continue?