Python Running Other Programs
subprocess runs another program from Python. run() starts it and brings back its output.
Run a tiny program
run() starts python3 with a small print. stdout holds the caught number.
import subprocess
result = subprocess.run(["python3", "-c", "print(2 + 3)"], capture_output=True, text=True)
print(result.stdout.strip())Read the return code
The small program exits with code 3. returncode brings that number back.
import subprocess
result = subprocess.run(["python3", "-c", "raise SystemExit(3)"], capture_output=True, text=True)
print(result.returncode)The output is text
stdout is text, so + "!" joins straight onto it. The printout proves it.
import subprocess
result = subprocess.run(["python3", "-c", "print(7)"], capture_output=True, text=True)
print(result.stdout.strip() + "!")Example
import subprocess
result = subprocess.run(["python3", "-c", "print(40 + 2)"], capture_output=True, text=True)
answer = result.stdout.strip()
print("Answer:", answer)
print("Code:", result.returncode)Key points
- subprocess: the module that runs other programs
- Use subprocess.run() to start one program
- Use capture_output=True to catch what the program prints
- Use text=True so the output comes back as text
- Use result.stdout to read the caught output
- Use result.returncode to check if the program worked
In this example, run() starts python3 with a small sum. capture_output catches the printed answer. text=True makes stdout plain text. strip() drops the newline from the answer. The printout shows the answer and the return code of zero.
Note
Without capture_output, the output goes to the screen, not to Python.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does capture_output=True do?