How to Run a Command from Python with subprocess.run
Sometimes the answer you need comes from another program: Git's commit hash, a tool's version, a file listing. subprocess.run starts the program from Python, waits for it to finish and hands you what it printed. This guide runs git --version, with real output from Python 3.15.2.
Syntax
result = subprocess.run([<program>, <argument>, ...], capture_output=True, text=True, check=True)
| Part | What it means |
|---|---|
[<program>, <argument>, ...] | The command as a list: the program, then each argument |
capture_output=True | Keeps what the program prints in result.stdout and result.stderr instead of showing it |
text=True | Gives that output as text rather than bytes |
check=True | Raises subprocess.CalledProcessError when the program fails |
Python's subprocess reference: "Run the command described by args. Wait for command to complete, then return a CompletedProcess instance." On check: "If check is true, and the process exits with a non-zero exit code, a CalledProcessError exception will be raised."
Prerequisites
- uv and Python, and Git for the example. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with
uv init.
Step 1: Write the Script
import subprocess
result = subprocess.run(
["git", "--version"], capture_output=True, text=True, check=True
)
print("Exit code:", result.returncode)
print("Output:", result.stdout.strip())

Step 2: Run It
uv run python run_command.py
Exit code: 0
Output: git version 2.56.1

Git ran and exited with 0, success, and result.stdout held what it printed. .strip() removed the line break at its end.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Leaving out capture_output=True | The program prints straight to the terminal, and result.stdout is None: the script printed git version 2.56.1, then stdout: None | Add capture_output=True |
Leaving out text=True | The output comes back as bytes: b'git version 2.56.1\n' | Add text=True |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
subprocess.CalledProcessError: Command ['git', 'rev-parse', 'HEAD'] returned non-zero exit status 128. | The program failed and check=True turned that into an exception; here Git wasn't in a repository | Catch the exception, or fix what made the program fail |
FAQ
Why a list and not one string?
Each item is passed to the program as one argument, exactly as written, so spaces and quotes inside an argument need no escaping.
How do I see the error a failed command printed?
With capture_output=True, it's in result.stderr, or in the exception's stderr when check=True raised one.
Conclusion
subprocess.run(["git", "--version"], capture_output=True, text=True, check=True) ran Git and returned exit code 0 and its output, git version 2.56.1.
Additional Resources
- subprocess.run — every parameter.
