Python subprocess.run: run a command, read output and exit code
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.
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:
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 4This 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):
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())
EOSCommand:
python3 s.pyRecorded output:
out errExit 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):
cat > s.py <<'EOS'
import subprocess
subprocess.run(['/nonexistent/prog'])
EOSCommand:
python3 s.pyRecorded 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
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.
All full guides: All guides