On this page
  1. subprocess
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Running a Command Safely with Timeout & Error Reporting
  7. 2. Streaming Line-by-Line Output with Popen
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

subprocess

Prev: struct | Up: stdlib_module | Next: symtable
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — subprocess
Tags: #public #python3 #stdlib


Import

import subprocess

Overview

Spawns external OS processes, connects to their stdin/stdout/stderr streams, enforces timeouts, and checks exit codes. Reach for subprocess.run() for 95% of use cases; drop down to subprocess.Popen only when you need incremental streaming or bidirectional IPC with a long-running child process.

Quick Start

import subprocess

result = subprocess.run(
    ["python3", "-c", "print('hello')"],
    capture_output=True,
    text=True,
    check=True,
    timeout=10,
)
assert result.stdout.strip() == "hello"

Implementation Walkthrough

1. Running a Command Safely with Timeout & Error Reporting

Pass arguments as a list[str] (never shell=True with user input) and set check=True + timeout:

import subprocess

def git_head_sha(repo_dir: str) -> str:
    try:
        proc = subprocess.run(
            ["git", "-C", repo_dir, "rev-parse", "--short", "HEAD"],
            capture_output=True,
            text=True,
            check=True,
            timeout=5,
        )
        return proc.stdout.strip()
    except subprocess.CalledProcessError as exc:
        raise RuntimeError(f"git failed ({exc.returncode}): {exc.stderr.strip()}") from exc
    except subprocess.TimeoutExpired as exc:
        raise TimeoutError("git rev-parse timed out") from exc

2. Streaming Line-by-Line Output with Popen

import subprocess

with subprocess.Popen(
    ["python3", "-c", "for i in range(3): print(i)"],
    stdout=subprocess.PIPE,
    text=True,
) as proc:
    assert proc.stdout is not None
    lines = [line.strip() for line in proc.stdout]
    assert proc.wait() == 0

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes