How do you run a shell command in Python and capture its output? | A1Lab@MZeeshanM to PythonEnglish • 5 days ago

How do you run a shell command in Python and capture its output?

message-square
0

Use subprocess.run(["cmd", "arg1"], capture_output=True, text=True, check=True) to execute an external command safely and read its standard output via result.stdout and standard error via result.stderr—avoiding os.system() (which cannot capture output) and avoiding shell=True unless shell features like pipes or wildcards are strictly required.

Basic Example

import subprocess

# 1. Recommended: Pass command and arguments as a list with capture_output=True & text=True
result = subprocess.run(
    ["python3", "--version"],
    capture_output=True,  # Captures both stdout and stderr
    text=True,            # Decodes bytes to str automatically (alias for encoding="utf-8")
    check=True,           # Raises CalledProcessError if exit code != 0
)

print("Exit code:", result.returncode)  # Output: 0
print("Stdout:", result.stdout.strip()) # Output: Python 3.x.x
print("Stderr:", result.stderr.strip()) # Output: (empty)

Key Details & Edge Cases

  • Pass arguments as a list[str] without shell=True (Security & Quoting):
    • Passing a list (["grep", "-rn", "my pattern", "./src"]) invokes the executable directly without spawning /bin/sh or cmd.exe, preventing shell injection vulnerabilities when filenames or variables contain spaces, quotes, or metacharacters (;, |, $()).
    • Use shell=True (with a single command string, e.g., subprocess.run("ls -la | grep .py", shell=True, capture_output=True, text=True)) only when you explicitly need shell pipelines, redirection (>), or glob expansion—and sanitize untrusted inputs with shutil.which() or shlex.quote().
  • Error handling (check=True vs. inspecting returncode):
    • With check=True, any non-zero exit status raises subprocess.CalledProcessError, exposing err.returncode, err.stdout, and err.stderr:
      try:
          res = subprocess.run(["ls", "/nonexistent"], capture_output=True, text=True, check=True)
      except subprocess.CalledProcessError as err:
          print(f"Command failed ({err.returncode}): {err.stderr.strip()}")
      
    • Without check=True (default check=False), subprocess.run() returns normally even when the command fails; always check if result.returncode != 0: before trusting result.stdout.
  • Setting timeouts and working directories (timeout, cwd, env):
    • Pass timeout=10 (in seconds) to abort hanging subprocesses with subprocess.TimeoutExpired.
    • Pass cwd="/path/to/dir" to run the command inside a specific directory without calling os.chdir().
  • Combining stdout and stderr into a single stream: If you want interleaved standard output and error output in exact chronological order, omit capture_output=True and pass stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True.
  • Streaming real-time output line-by-line (subprocess.Popen): subprocess.run() buffers all output in memory until the command exits. For long-running commands (like docker build or pytest) where you need live line-by-line output while capturing it, iterate over Popen.stdout:
    lines = []
    with subprocess.Popen(
        ["ping", "-c", "3", "127.0.0.1"],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True,
    ) as proc:
        for line in proc.stdout:
            print(line, end="")  # Stream live to console
            lines.append(line)