---
title: "Python Subprocess: Run Shell Commands Safely and Capture Output"
description: "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."
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/codesnippets/post/python-subprocess-run-shell-commands-safely
---

# Python Subprocess: Run Shell Commands Safely and Capture Output

**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:

```python

# 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 same user input, two ways of running a command_

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.

`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

```python title="run_command.py" showLineNumbers
"""Run external commands without handing a stranger a shell prompt."""

from __future__ import annotations

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

```python
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.

```python
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

```python
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:

    return json.loads(run(["kubectl", *args, "-o", "json"], timeout=30).out)
```

### Entry point

```python
if __name__ == "__main__":

    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)
```

`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

```bash
# Normal use
python run_command.py

# Watch what is being executed, without guessing
python -c "

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

| Approach                                | When it fits                                                                                                 |
| --------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| `subprocess.run` with a list            | The default. Use this unless you have a specific reason not to.                                              |
| `subprocess.Popen`                      | You need output live, or you need to talk to the process while it runs.                                      |
| `shell=True` with a fully static string | You genuinely need a pipe or a glob and no user input is involved.                                           |
| `plumbum` or `sh`                       | You are writing a lot of shell-like Python and want a nicer syntax. Both wrap subprocess.                    |
| A real library                          | Before 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.
