subprocess in Python
run a command, capture its output, and check the exit code.
import subprocess
import sys
done = subprocess.run(
[sys.executable, "-c", "print('from a child')"],
capture_output=True, text=True, check=True)
print(done.returncode, done.stdout.strip())
failed = subprocess.run([sys.executable, "-c", "raise SystemExit(3)"],
capture_output=True, text=True)
print(failed.returncode)
try:
subprocess.run([sys.executable, "-c", "raise SystemExit(1)"], check=True)
except subprocess.CalledProcessError as exc:
print("raised:", exc.returncode)
How it works
capture_output=Truecollects stdout and stderr.check=Trueraises when the command fails.- Pass a list, never a string, unless you truly want a shell.
Keywords and builtins used here
asexceptprinttry
The run, in numbers
- Lines
- 17
- Characters to type
- 477
- Tokens
- 129
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 74 seconds.
Step 4 of 4 in Command line, step 25 of 41 in Domain tools.