Sheet ⁨05⁩ · ⁨Code snippets⁩Surveyed ⁨2026⁩

Blog post image for Python Subprocess: Run Shell Commands Safely and Capture Output - A Python snippet covering the right way to run external shell commands using subprocess.run(). Explains why os.system and shell=True are dangerous, how to capture stdout and stderr, handle non-zero exit codes with CalledProcessError, set timeouts, and stream output live with Popen.

Python Subprocess: Run Shell Commands Safely and Capture Output

Published: Updated: 06 Mins read
Markdown for AI(opens in a new tab)

Quick Tip

Pass a list, never a string, and subprocess never starts a shell at all. That one habit removes an entire category of vulnerability from your automation.

The Problem

Every script eventually needs to run something else

The Problem

Python is great until you need git, kubectl, docker, or the AWS CLI. There is no library call for git rev-parse HEAD that is simpler than just running it, so you shell out. The trouble starts with how you do it.

Three patterns show up constantly, and all three are wrong in different ways:

import os, subprocess
# 1. Returns a wait status, not an exit code. You cannot capture output.
# Always uses a shell. There is no scenario where this is the best tool.
os.system(f"git checkout {branch}")
# 2. Deprecated since Python 2.6. Still turns up in tutorials.
os.popen(f"git log --oneline {ref}").read()
# 3. Modern API, but shell=True hands the whole string to /bin/sh.
subprocess.run(f"git checkout {branch}", shell=True)

The third one is the dangerous one, because it looks modern and correct. subprocess.run is the right function. shell=True is what breaks it.

What it actually costs

A shell parses semicolons, pipes, backticks, $(), globs, and redirects. It has no idea which part of your string you wrote and which part came from a pull request title, a filename, or a form field.

The only difference is who parses the string. With shell=True, /bin/sh does, and it does its job perfectly: it sees a semicolon and runs two commands. With a list, nothing parses anything and the semicolon is just an odd character in a filename.

The failure mode that is easier to hit than injection is silence. Without check=True, a command that fails returns normally and your script carries on as if everything worked. You find out three steps later, when something else breaks for a reason that makes no sense.

Careful here

shell=True is not banned outright. It is correct when you wrote the entire string yourself and genuinely need shell features such as a pipe or a glob. The rule is that no part of that string may come from outside your program. If you find yourself reaching for shlex.quote() to make it safe, pass a list instead. Quoting correctly is harder than not needing to.

The Solution

One function, a list of arguments, and three keyword arguments

The Fix

subprocess.run() with a list. Python calls execve directly, no shell is involved, and every list element arrives at the program as exactly one argument no matter what is inside it.

The three keyword arguments that matter

capture_output=True collects stdout and stderr separately. text=True decodes them to str rather than handing you bytes. check=True raises CalledProcessError on a non-zero exit instead of returning a result you might forget to inspect.

Everything below is built from those three plus a timeout.

Script Implementation

Setup and a safe wrapper

run_command.py
"""Run external commands without handing a stranger a shell prompt."""
from __future__ import annotations
import logging
import shutil
import subprocess
from dataclasses import dataclass
from typing import Sequence
log = logging.getLogger(__name__)
# Anything unattended needs a ceiling. A command waiting on a prompt you
# cannot see will wait until someone kills the job.
DEFAULT_TIMEOUT = 60
@dataclass(frozen=True)
class Result:
"""What the caller usually wants, without the full CompletedProcess."""
code: int
out: str
err: str
@property
def ok(self) -> bool:
return self.code == 0

The core helper

def run(
args: Sequence[str],
*,
check: bool = True,
timeout: int = DEFAULT_TIMEOUT,
cwd: str | None = None,
env: dict[str, str] | None = None,
) -> Result:
"""Run a command from a list of arguments. No shell, ever.
args must be a list. If you pass a string here, Python treats the
whole thing as the program name and you get FileNotFoundError with a
confusing message, which is a much better failure than shell=True.
"""
if isinstance(args, str):
raise TypeError("pass a list of arguments, not a string")
# A clearer error than the one execve gives, and it catches a missing
# binary in CI before the command is half done.
if shutil.which(args[0]) is None:
raise FileNotFoundError(f"{args[0]} is not on PATH")
log.debug("running %s", args)
try:
proc = subprocess.run(
args,
capture_output=True,
# text=True decodes to str. Pin the encoding and replace bad
# bytes, because some tools emit output that is not valid
# UTF-8 and a decode error at 3am is a poor way to learn that.
text=True,
encoding="utf-8",
errors="replace",
timeout=timeout,
cwd=cwd,
env=env,
check=check,
)
except subprocess.CalledProcessError as exc:
# stderr is on the exception too. Logging it here is the single
# most useful thing you can do for whoever reads the CI output.
log.error("%s exited %d: %s", args[0], exc.returncode, exc.stderr.strip())
raise
except subprocess.TimeoutExpired as exc:
# run() kills the child before raising, but a child that spawned
# its own children can leave orphans. See the note below.
log.error("%s timed out after %ss", args[0], exc.timeout)
raise
return Result(proc.returncode, proc.stdout.strip(), proc.stderr.strip())

When you need output as it happens

subprocess.run buffers everything until the process exits. That is fine for git rev-parse and useless for a docker build that takes four minutes and prints progress the whole time.

def stream(args: Sequence[str], cwd: str | None = None) -> int:
"""Run a command and print its output live. Returns the exit code."""
with subprocess.Popen(
args,
stdout=subprocess.PIPE,
# Merge stderr into stdout so the interleaving matches what you
# would see in a terminal. Keep them separate if you need to
# tell them apart.
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
errors="replace",
# Line buffered. Without this you get output in 8KB lumps and
# the "live" streaming is not live at all.
bufsize=1,
cwd=cwd,
) as proc:
# proc.stdout is None only if stdout was not a pipe, which it is.
assert proc.stdout is not None
for line in proc.stdout:
print(line.rstrip())
return proc.returncode

Wrapping a real tool

def git(*args: str, cwd: str | None = None) -> str:
"""Thin git wrapper. Every argument stays one argument."""
return run(["git", *args], cwd=cwd).out
def current_branch(repo: str) -> str:
return git("rev-parse", "--abbrev-ref", "HEAD", cwd=repo)
def checkout(repo: str, ref: str) -> None:
# ref could be anything, including "main; rm -rf /". It arrives at
# git as one argument and git rejects it as an unknown revision.
git("checkout", ref, cwd=repo)
def kubectl_json(*args: str) -> dict:
import json
return json.loads(run(["kubectl", *args, "-o", "json"], timeout=30).out)

Entry point

if __name__ == "__main__":
import sys
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
try:
print(current_branch("."))
sys.exit(stream(["git", "status", "--short"]))
except subprocess.CalledProcessError as exc:
# The helper already logged stderr, so just exit with the same
# code the child used. CI reads that number.
sys.exit(exc.returncode)
except (FileNotFoundError, subprocess.TimeoutExpired) as exc:
log.error("%s", exc)
sys.exit(1)

Note

timeout= kills the direct child, not its grandchildren. If the command starts its own subprocesses, those can survive as orphans. When that matters, start the child in its own process group with start_new_session=True and send the signal to the group with os.killpg, which is a few more lines than most scripts need but the correct answer for a long-running worker.

Usage and Benefits

Why this helps

Why This Helps

The list form removes shell injection completely, because there is no shell to inject into. check=True turns a silent wrong answer into a stack trace at the point of failure. timeout= turns a hung CI job into an error you can retry. None of those are optional in automation, and together they are about four extra characters per call.

You also get output you can actually use. capture_output=True with text=True gives you str on both streams, separately, so you can log stderr and parse stdout without untangling them.

Running it

Terminal window
# Normal use
python run_command.py
# Watch what is being executed, without guessing
python -c "
import logging, run_command
logging.basicConfig(level=logging.DEBUG)
print(run_command.current_branch('.'))
"
bash
$

Community Discussion

Your turn

Your Turn

Most codebases have at least one shell=True left in them, usually in a deploy script written in a hurry. Search yours: grep -rn "shell=True" . takes a second and the results are always interesting. How many of them interpolate a variable?

Alternative approaches

ApproachWhen it fits
subprocess.run with a listThe default. Use this unless you have a specific reason not to.
subprocess.PopenYou need output live, or you need to talk to the process while it runs.
shell=True with a fully static stringYou genuinely need a pipe or a glob and no user input is involved.
plumbum or shYou are writing a lot of shell-like Python and want a nicer syntax. Both wrap subprocess.
A real libraryBefore wrapping a CLI, check for a client. boto3, the Kubernetes Python client, and GitPython all exist.

The last row is worth taking seriously. Wrapping aws s3 cp when boto3 is installed means parsing text output and losing typed errors. Shell out when there is no library, not by habit.

Was this useful?

You might also enjoy

More posts on similar topics

Python Async HTTP Requests with aiohttp: Fetch Multiple URLs Concurrently

Python Async HTTP Requests with aiohttp: Fetch Multiple URLs Concurrently

Quick Tip Reuse one aiohttp session, fan your requests out with asyncio.gather, and cap them with a semaphore to fetch hundreds of URLs in the time one loop would take. The Problem **The

List S3 Buckets

List S3 Buckets

Overview Multi-profile S3 management Ever juggled multiple AWS accounts and needed a quick S3 bucket inventory across all of them? This Python script handles it. Use case Perfect for or

Multi-Environment Secret Management with HashiCorp Vault

Multi-Environment Secret Management with HashiCorp Vault

Managing secrets safely across multiple environments with HashiCorp Vault Storing secrets in .env files, hardcoding them, or even using separate secret managers per environment creates security

AWS EC2 Instance Management with Boto3: Start, Stop, and Query Instances

AWS EC2 Instance Management with Boto3: Start, Stop, and Query Instances

If you've ever spent 20 minutes clicking through the AWS Console just to stop a handful of dev instances, you already know the pain. It's tedious, it doesn't scale, and one wrong click can ruin your a

Bash Retry Function: Automatically Retry Failing Commands with Exponential Backoff

Bash Retry Function: Automatically Retry Failing Commands with Exponential Backoff

Quick Tip Wrap any flaky command in one reusable retry function and stop re-running red pipelines by hand. The Problem The Problem Some commands fail for reasons that have nothing to

Essential Bash Variables for Every Script

Essential Bash Variables for Every Script

Overview Quick Tip You know what's worse than writing scripts? Writing scripts that break every time you move them to a different machine. Built-in Bash variables fix that. The problem wi

6 related posts