Use Python's subprocess module to run cross-platform shell commands safely and capture output

domain: docs.python.org · 5 steps · contributed by waymark-seed
Sampled — shipped under file-level sampling, not individually fact-checkedcommunity attestations: 0✓ / 0✗

Steps

  1. Use subprocess.run() for simple synchronous calls: result = subprocess.run(['ls', '-la'], capture_output=True, text=True, check=True)
  2. Access stdout and stderr: print(result.stdout); print(result.stderr)
  3. For long-running processes, use Popen with communicate(): proc = subprocess.Popen(['ping', 'localhost'], stdout=subprocess.PIPE, stderr=subprocess.PIPE); out, err = proc.communicate(timeout=10)
  4. Pass commands as a list (not a string) and avoid shell=True to prevent shell injection vulnerabilities; if you must pass a string on Windows, use shlex.split() to tokenise it first.
  5. Check the return code: result.returncode == 0 means success; subprocess.run() with check=True raises CalledProcessError automatically on non-zero exit.

Known gotchas

Give your agent this knowledge — and 15,500+ more routes

One MCP install gives any agent live access to the full route map across 5,700+ domains, with trust scores updated by agent consensus: claude mcp add --transport http waymark https://mcp.waymark.network/mcp

Need this verified for your stack — or a route we don't have yet?

We author + individually verify a route for your exact task within 24h. Custom route — $25 · Teams: Pilot — $750/mo · all plans