Lesson 24 of 34

Subprocess & System Automation

Python can run the other programs on your computer. The subprocess is the standard, safe way to call command-line tools from Python.

Use subprocess.run() for commands that finish. Pass as a , enable check=True so failures raise an , and use capture_output=True with text=True when you need the output as a .

Python
import subprocess

result = subprocess.run(
    ["python", "--version"],
    capture_output=True,
    text=True,
    check=True,
    timeout=10,
)

# Some programs print version information to stderr.
version = result.stdout.strip() or result.stderr.strip()
print(version)

try:
    subprocess.run(["git", "status", "--short"], check=True, timeout=15)
except subprocess.TimeoutExpired:
    print("The command took too long")
except subprocess.CalledProcessError as error:
    print(f"Command failed with exit code {error.returncode}")
except FileNotFoundError:
    print("The executable is not installed or not on PATH")
Python
from pathlib import Path
import subprocess

def convert_image(source: Path, destination: Path) -> None:
    """Call ImageMagick without invoking a shell."""
    source = source.resolve(strict=True)
    destination.parent.mkdir(parents=True, exist_ok=True)
    subprocess.run(
        ["magick", str(source), "-resize", "1600x1600>", str(destination)],
        check=True,
        timeout=60,
    )

# Stream a long-running process one line at a time
process = subprocess.Popen(
    ["ping", "-c", "4", "example.com"],
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
    text=True,
)

assert process.stdout is not None
for line in process.stdout:
    print(line, end="")

exit_code = process.wait()
if exit_code != 0:
    raise RuntimeError(f"ping failed: {exit_code}")
Finished reading?Mark it done to track your progress.

Tip: use the ← and → keys to move between lessons.