Python subprocess Output and Return Codes
Running a command is half the job; reacting to what it did is the other half. check=True turns a non-zero exit into an exception carrying both streams, text=True decides whether you get str or bytes, and input= feeds a command on standard input without a temporary file. All four decisions matter in a script nobody is watching.
OS and Process Automation Guide 18 of 39 Intermediate
- Control nodeUbuntu 26.04 LTS
- Python3.14.4
- requests2.34.2
- paramiko5.0.0
- TimeAbout 15 min
capture_output=True needs Python 3.7; before that it was stdout=PIPE, stderr=PIPE. text=True and its older spelling universal_newlines=True are the same argument.
- pytest9.1.1
- PyYAML6.0.3
- boto3 / botocore1.43.78
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| RUNNER01 | 192.168.0.27 | Ubuntu 26.04 LTS | Control node - every script in this path runs here | 2 Core | 4 GB | 50 GB |
This guide includes
Use this once the command runs and you have to react to what it did. This matters because without check=True a failing command is only a return value, and nothing makes you look at it.
- using
check=True, so a failure is an exception - separating text from bytes
- feeding something on standard input
- putting the last two guides together into the shape worth copying
Before you start
-
check=True, so a failure is an exception
-
text against bytes
-
Feeding something on standard input
-
The shape to copy