typestar

subprocess in Python

run a command, capture its output, and check the exit code.

import subprocess
import sys

done = subprocess.run(
    [sys.executable, "-c", "print('from a child')"],
    capture_output=True, text=True, check=True)

print(done.returncode, done.stdout.strip())

failed = subprocess.run([sys.executable, "-c", "raise SystemExit(3)"],
                        capture_output=True, text=True)
print(failed.returncode)

try:
    subprocess.run([sys.executable, "-c", "raise SystemExit(1)"], check=True)
except subprocess.CalledProcessError as exc:
    print("raised:", exc.returncode)

How it works

  1. capture_output=True collects stdout and stderr.
  2. check=True raises when the command fails.
  3. Pass a list, never a string, unless you truly want a shell.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
477
Tokens
129
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 74 seconds.

Type this snippet

Step 4 of 4 in Command line, step 25 of 41 in Domain tools.

← Previous Next →