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