Sub topic 1
Why use subprocess instead of os.system
Prerequisites
This chapter assumes you know the following:
- Basic Python syntax, functions, and exceptions.
- How to use a terminal.
- That programs have standard input, standard output, and standard error.
- The difference between text (
str) and bytes in Python.
What os.system does
os.system takes one string and hands it to the operating system's shell. The shell parses the string, runs the command, and os.system returns a number. Nothing else comes back.
import os
status = os.system("echo hello")
print("status:", status)The output hello goes straight to your terminal. Your program never receives it as a value. The number is also hard to read. On Unix it is a packed wait status, so os.system("exit 3") returns 768, which is the exit code 3 shifted left by 8 bits. On Windows it is the plain exit code.
What goes wrong with os.system
- No captured output. You cannot get stdout or stderr into a variable.
- No input. You cannot send data to the command's stdin.
- No timeout. A hung command hangs your program.
- No exceptions. A failing command returns a non-zero number, and your code continues if you forget to check it.
- Always a shell. Every string is parsed by a shell. If the string includes untrusted text, that text can run as commands.
The standard library documentation recommends subprocess over os.system for these reasons.
What subprocess gives you
subprocess.run starts a child process, waits for it, and returns a CompletedProcess object. It takes a list of arguments, so no shell is involved by default.
import subprocess
import sys
result = subprocess.run(
[sys.executable, "-c", "print('hello')"],
capture_output=True,
text=True,
check=True,
)
print(result.stdout.strip())
print(result.returncode)This prints hello and then 0. Each argument does one job:
capture_output=Truecollects stdout and stderr instead of printing them.text=Truedecodes them tostr.check=Trueraises an exception if the exit code is not zero.
Using sys.executable runs the same Python interpreter that runs your script, so the example works on any operating system.
Comparison
| Need | os.system | subprocess.run |
|---|---|---|
| Read output | No | `capture_output=True` |
| Send input | No | `input=...` |
| Stop a hung command | No | `timeout=...` |
| Raise on failure | No | `check=True` |
| Avoid the shell | No | Default with a list |
Common mistake
Switching to subprocess.run but passing a single string with shell=True keeps the main risk of os.system. Use a list of arguments unless you have a specific reason to use a shell. Later chapters explain when that is acceptable.
Exercise
A script calls os.system("ls missingfolder") on Linux and ignores the return value. Give two reasons this is a weaker design than subprocess.run(["ls", "missingfolder"], check=True).
Show answer
os.system does not raise an exception when the command fails, so the script continues as if nothing happened. It also cannot capture the error message from stderr, because the message goes to the terminal. With check=True, subprocess.run raises CalledProcessError on a non-zero exit code. Passing capture_output=True gives access to the error text. Other valid reasons are that os.system always uses a shell and has no timeout.