Sub topic 1
Why use subprocess instead of os.system
Python programs often need to run something else: git, ffmpeg, a compiler, or another Python script. os.system is the oldest way to do it and also the weakest. This chapter explains what os.system does, where it fails, and why the subprocess module is the standard replacement. Later chapters cover each subprocess feature in detail. This one gives you the reasons to switch.
Prerequisites
This chapter assumes you know:
- Basic Python syntax, functions and exceptions.
- How to use a terminal and run a command there.
- That every program has standard input (stdin), standard output (stdout) and standard error (stderr).
- The difference between text (
str) and bytes (bytes) in Python.
All examples use sys.executable, the path of the running Python interpreter. This lets them run on any system without needing outside tools. One example uses Unix shell behavior, and it is marked.
What os.system does
os.system(command) takes one string and passes it to the system shell. On Linux and macOS that is usually /bin/sh. On Windows it is cmd.exe. The shell parses the string, starts the program, and waits for it to finish. os.system then returns a number.
import os
import sys
status = os.system(f'"{sys.executable}" -c "import sys; sys.exit(3)"')
print("status:", status)On Windows this prints status: 3. On Linux and macOS it prints status: 768. On Unix the return value is a wait status, which packs the exit code into the high byte (3 × 256 = 768). The same call returns different numbers on different systems, and you have to decode the number yourself.
The problems with os.system
os.system is easy to write, but it limits what you can do.
- No captured output. The child writes straight to your program's stdout and stderr. You cannot put its output in a variable.
- No input. You cannot send data to the child's stdin from Python.
- No timeout. If the command hangs, your program hangs with it.
- No exceptions. A failing command only gives a non-zero number. If you forget to check the number, the failure goes unnoticed.
- A confusing return value. The meaning of the number depends on the platform.
- Shell injection risk. Any text you put into the command string is parsed by the shell.
- No control over the environment. You cannot easily give the child a different working directory or different environment variables.
The Python documentation recommends subprocess over os.system for these reasons.
The same job with subprocess.run
subprocess.run is the main entry point of the subprocess module. It starts a child process, waits for it to finish, and returns a CompletedProcess object. That object holds the arguments, the return code, and any captured output.
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. Four things differ from os.system:
- The command is a list, so Python starts the program directly without a shell.
capture_output=Truecollects stdout and stderr instead of printing them.text=Truedecodes the output into astrinstead ofbytes.check=Trueraises an exception if the exit code is not zero.
The return code is result.returncode on every platform. Here it is 0.
Comparing the two
| Need | os.system | subprocess.run |
|---|---|---|
| Command format | One string, parsed by a shell | A list of arguments, no shell by default |
| Read the output | Not possible | `capture_output=True` |
| Send input | Not possible | `input=...` |
| Detect failure | Inspect a platform-specific number | `returncode`, or `check=True` raises `CalledProcessError` |
| Stop a hung command | Not possible | `timeout=...` raises `TimeoutExpired` |
| Change environment or directory | Awkward, through the shell | `env=...` and `cwd=...` |
| Handling untrusted text | Easy to get wrong | Safe when passed as list items |
Failure becomes an exception
With os.system, a failed command is silent unless you remember to check. With check=True, a failure raises CalledProcessError, which carries the exit code and the command.
import subprocess
import sys
try:
subprocess.run(
[sys.executable, "-c", "import sys; sys.exit(3)"],
check=True,
)
except subprocess.CalledProcessError as exc:
print("command failed with code", exc.returncode)This prints command failed with code 3. The code is the same on every platform, because subprocess reports the real exit code and not a wait status.
Hung commands can be stopped
A child that never finishes can freeze your program. subprocess.run accepts a timeout in seconds. When the time runs out, run kills the child and raises TimeoutExpired.
import subprocess
import sys
try:
subprocess.run(
[sys.executable, "-c", "import time; time.sleep(10)"],
timeout=1,
)
except subprocess.TimeoutExpired as exc:
print("timed out after", exc.timeout, "seconds")This prints timed out after 1 seconds after about one second. With os.system the same program would wait the full ten seconds.
Shell injection
The most serious problem with os.system is security. When you build a command string from outside data, the shell treats characters such as ;, &&, | and $() as syntax, not as plain text. An attacker, or just an unusual file name, can add extra commands.
The next example is for Linux and macOS. The injected command is harmless, but it shows the problem.
import os
user_value = "report.txt; echo injected"
# The shell sees two commands: "echo report.txt" and "echo injected".
os.system("echo " + user_value)This prints two lines, report.txt and injected. The second line shows that the text after the semicolon ran as its own command. If that command had been rm instead of echo, it would have deleted files.
With subprocess, you pass a list. Each item is delivered to the program as exactly one argument, and no shell reads it.
import subprocess
import sys
user_value = "report.txt; echo injected"
subprocess.run(
[sys.executable, "-c", "import sys; print(sys.argv[1])", user_value],
)This prints the full text report.txt; echo injected on one line. Python treated the semicolon as ordinary text. A later chapter covers shell=True and shlex in more detail.
How the two paths differ
The shell step is the only difference in the path, and it is where injection and platform quirks come from. Skipping it also makes the call a little faster, because Python does not start an extra shell process.
When os.system is still acceptable
os.system is not removed from Python, and it does work. For a throwaway script where you type every command yourself, run it once, and do not care about its output, it is fine. Once a command comes from input, needs checking, or runs in code that others depend on, use subprocess.
Other things to know
- Older helpers.
subprocess.call,check_callandcheck_outputcome from older Python versions.run, added in Python 3.5, covers all of them, so new code should userun. - Where
subprocessfits.runhandles most jobs. For streaming output, pipelines, and finer control, the module also provides thePopenclass. Later chapters cover it. - Bytes by default. Without
text=True, captured output isbytes. This matters when the child prints non-text data or an encoding you did not expect.
Exercise
A script calls os.system("grep " + word + " notes.txt") where word comes from a web form. Name two problems with this call, then show how to rewrite it with subprocess.run so the output is captured as text and a failing grep raises an exception. (Hint: grep exits with 1 when it finds no match, which check=True also treats as a failure.)
Show answer
Problems: (1) word is joined into a shell string, so input like "x; rm -rf ~" runs extra commands (shell injection); (2) the output goes to the terminal and cannot be captured, and the return value is a platform-specific wait status that is easy to ignore. Rewrite: subprocess.run(["grep", word, "notes.txt"], capture_output=True, text=True, check=True). The word is passed as a single argument with no shell, result.stdout holds the matching lines as a str, and a non-zero exit code raises CalledProcessError. Because grep returns 1 when nothing matches, a careful program would catch CalledProcessError and check exc.returncode == 1 to treat "no match" differently from a real error. A word that starts with "-" could still be read as an option, so putting "--" before it is a good habit.
Exercise
On Linux, os.system runs a command that exits with code 2, and it returns 512. Why, and how does subprocess.run report the same exit?
Show answer
On Unix, os.system returns the wait status, which stores the exit code in the high byte: 2 × 256 = 512. subprocess.run returns a CompletedProcess whose returncode is 2 on every platform. With check=True it raises CalledProcessError with exc.returncode equal to 2.