subprocess
The subprocess module lets you run another program or command from Python and capture what it prints.
Used in 15 lessons of the course, from 00.02.
subprocess is a standard library module. With it, your Python code starts another program, as if you typed it in the terminal.
The function you will use most is subprocess.run(). It takes a list: the first item is the program and the rest are its arguments. A list avoids problems with spaces and is safer than building a command string.
With capture_output=True you keep what the program prints, and with text=True you get it as a string instead of bytes. run() returns an object with stdout, stderr and returncode (0 means everything went fine).
In the course you see it from lesson 00.02 with import subprocess, usually to install packages or run commands from a script.
r = subprocess.run(["python", "--version"], capture_output=True, text=True)
Reach for it when: you need to run another program or system command from Python and read its output or exit code.
Examples
Common mistake
import subprocess
import sys
r = subprocess.run([sys.executable, "-c", "print('hi')"])
print(repr(r.stdout))Why: Without capture_output=True, the program prints straight to your terminal and r.stdout stays None.
How to write it: Pass capture_output=True and text=True to receive the text in r.stdout.
Common mistake
import subprocess subprocess.run(["programa_que_no_existe_xyz"])
Why: If the program does not exist, Python cannot start it and raises an exception instead of returning an error code.
How to write it: Check the program name or catch FileNotFoundError with try / except.
