brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's subprocess.run with check=True stops on a failed command

Python
~/tips/tip-python-subprocess-run-check

import subprocess

Run a shell command from Python, capture its output and fail loudly on errors.

By default subprocess.run happily carries on when the command fails. I’d almost always add three arguments to it.

import subprocess

result = subprocess.run(
    ["git", "rev-parse", "HEAD"],
    check=True, capture_output=True, text=True,
)
print(result.stdout.strip())

check=True raises CalledProcessError when the exit code isn’t 0, so a failed command can’t slip by. capture_output=True collects stdout and stderr instead of letting them run through to your terminal, and text=True gives you strings instead of bytes.

When it does fail, the exception carries everything you need: e.returncode, e.stdout and e.stderr. I’d print e.stderr in the except block, because that’s where the real reason is.

I pass the command as a list on purpose. Each argument goes to the program as is, so a file name with spaces or a semicolon can’t turn into a second command. With shell=True and a string you’re back to shell quoting rules, and with user input in that string that becomes a security problem.

For commands that print a lot or run for a long time, leave capture_output off so you can watch the progress live.

Further reading: subprocess.run

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link