# Python subprocess.run: run a command, read output and exit code

Published: 2026-11-30
Updated: 2026-12-01

Rights: original
Source: https://kairos-2z6s.onrender.com/res/python-subprocess-full-en
`subprocess.run` starts a program, waits for it and returns a result object with the exit status, stdout and stderr. Passing a list of arguments avoids shell parsing; `check=True` raises when the exit status is not zero.

Each command below is the exact command that was run and each output block is copied from the recorded log. Test ids, log hashes and exit statuses are in the evidence table.

(Test: 3 tests were run, TE-54-A, TE-54-B and TE-54-C. The expected non-zero exit is TE-54-C (exit status 1). Every row has a recorded log, and the exit statuses and log hashes are in the evidence table.)

### TE-54-A: subprocess.run does not capture output unless asked, and check=True raises on a non-zero exit

No setup needed: the command below creates what it uses in the throwaway folder.

Command:

```bash
python3 -c "import subprocess; r=subprocess.run(['bash','-c','echo hi']); print('default', r.stdout, r.returncode); r2=subprocess.run(['bash','-c','echo hi'], capture_output=True, text=True); print('captured', repr(r2.stdout)); r3=subprocess.run(['bash','-c','exit 3'], capture_output=True); print('code', r3.returncode)
try:
    subprocess.run(['bash','-c','exit 4'], check=True, capture_output=True)
except subprocess.CalledProcessError as e:
    print('raised', e.returncode)"
```

Recorded output:

```
hi
default None 0
captured 'hi\n'
code 3
raised 4
```

This run checks the exit status and records the output; it asserts no expected text.

Exit status: 0. This is the status recorded in the log for TE-54-A.

### TE-54-B: capture_output keeps standard output and standard error apart

Setup for this run, inside a throwaway directory (`mktemp -d`):

```bash
cat > s.py <<'EOS'
import subprocess
r = subprocess.run(['bash', '-c', 'echo err >&2; echo out'], capture_output=True, text=True)
print(r.stdout.strip(), r.stderr.strip())
EOS
```

Command:

```bash
python3 s.py
```

Recorded output:

```
out err
```

Exit status: 0. This status and the output match what was written before the run.

### TE-54-C: expected non-zero exit: running a program at a path that does not exist raises FileNotFoundError

Setup for this run, inside a throwaway directory (`mktemp -d`):

```bash
cat > s.py <<'EOS'
import subprocess
subprocess.run(['/nonexistent/prog'])
EOS
```

Command:

```bash
python3 s.py
```

Recorded output: none, standard output was empty.

Standard error from the same run:

```
Traceback (most recent call last):
  File "/tmp/b26-9z78nh2l/work/s.py", line 2, in <module>
    subprocess.run(['/nonexistent/prog'])
  File "/usr/lib/python3.10/subprocess.py", line 503, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/usr/lib/python3.10/subprocess.py", line 971, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/usr/lib/python3.10/subprocess.py", line 1863, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: '/nonexistent/prog'
```

Exit status: 1. This status matches the corrected expectation, written after a first run that did not match. The first prediction used subprocess.run(['nosuchprogram']). On the recording machine that name lookup raised PermissionError: [Errno 13] Permission denied instead of FileNotFoundError, and I did not investigate the cause. The test was changed to an absolute path that does not exist, and all tests were run again. The path in the traceback line is a temporary folder and differs on each machine and each run.

TE-54-B: with capture_output=True, r.stdout holds out and r.stderr holds err, so the program printed out err. TE-54-C: running a program at a path that does not exist stopped with exit status 1. The last line of standard error is FileNotFoundError: [Errno 2] No such file or directory: '/nonexistent/prog'.

## Limits

The runs here cover argument lists, captured output, check=True and the return code. Running through a shell (`shell=True`) is not tested on this page.

## Source

- https://docs.python.org/3/library/subprocess.html

## Evidence

- `TE-54-A`: subprocess.run does not capture output unless asked, and check=True raises on a non-zero exit

- logs: one recorded log for each row above
- Recorded on: Linux x86_64, kernel 7.3.4; bash 5.1.16; git 2.34.1; python 3.10.12; findutils 4.8.0; grep 3.7; sed 4.8; gawk 5.1.0; tar 1.34; curl 7.81.0. Locale C.UTF-8, TZ=UTC.

## Evidence table

| Test | What it checks | Exit | Verdict | Log sha256 (first 12) |
|---|---|---|---|---|
| `TE-54-A` | subprocess.run does not capture output unless asked, and check=True raises on a non-zero exit | 0 | PASS | `b5460d4f592b` |
| `TE-54-B` | capture_output keeps standard output and standard error apart | 0 | PASS | `00fe924eda07` |
| `TE-54-C` | expected non-zero exit: running a program at a path that does not exist raises FileNotFoundError | 1 | PASS | `f10a5aff57f7` |

Every row has a recorded log holding the setup commands, the command, stdout, stderr, exit status and the final directory state. The first 12 characters of the log's sha256 are in the table.

## Related guides
- [Python Sets: unique items and set operations](https://kairos-2z6s.onrender.com/res/python-sets-full-en)
- [Python enumerate, zip and range: loop with an index or two lists](https://kairos-2z6s.onrender.com/res/python-enumerate-zip-range-full-en)
- [Python sys.exit: set the exit status](https://kairos-2z6s.onrender.com/res/python-sys-exit-full-en)
- [Python string methods: strip, split, replace and friends](https://kairos-2z6s.onrender.com/res/python-string-methods-full-en)
- [Python str.join: build a string from a list](https://kairos-2z6s.onrender.com/res/python-str-join-full-en)
