Sometimes the easiest way to get a job done is to run another program: a Git command, a backup tool, a converter or another Python script. The subprocess module lets your Python code start other programs, pass them input, read what they print and check whether they worked. This lesson covers subprocess.run and how to use it safely.
In this lesson you will learn
- Running a command with
subprocess.run - Reading output, error output and the return code
- Handling failures with
check=Trueandtimeout - Sending input and setting environment variables
- Why you should pass a list and avoid
shell=True
You should know exception handling and modules.
About the examples
The examples use echo, ls and sort, which exist on Linux and macOS. On Windows, use commands that exist there, or run Python itself with sys.executable as the examples also do.
Running a Command
import subprocess
import sys
# Run a command and capture what it prints
result = subprocess.run(["echo", "Hello from the shell"], capture_output=True, text=True)
print("return code:", result.returncode)
print("output:", result.stdout.strip())
# Run another Python program (sys.executable is the current Python)
code = "import sys; print(sum(range(1, 101))); print('done', file=sys.stderr)"
r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)
print("stdout:", r.stdout.strip(), "| stderr:", r.stderr.strip())
# A failing command: returncode is not 0
r = subprocess.run(["ls", "/no/such/folder"], capture_output=True, text=True)
print("ls failed? (return code is not 0)", r.returncode != 0)
# check=True turns failure into an exception
try:
subprocess.run(["ls", "/no/such/folder"], capture_output=True, text=True, check=True)
except subprocess.CalledProcessError as e:
print("CalledProcessError, exit status", e.returncode)
# A command that does not exist at all
try:
subprocess.run(["no-such-program"])
except FileNotFoundError:
print("FileNotFoundError: program not found")
Output
return code: 0
output: Hello from the shell
stdout: 5050 | stderr: done
ls failed? (return code is not 0) True
CalledProcessError, exit status 2
FileNotFoundError: program not found
- The command is a list: the program name first, then each argument as its own item.
capture_output=Truecollects what the program prints instead of showing it on screen.text=Truegives you strings instead of bytes.- The result has three useful parts:
stdout(normal output),stderr(error messages) andreturncode. - A return code of 0 means success. Any other number means the program reported a problem.
sys.executableis the path of the Python that is running now, so[sys.executable, "-c", code]runs Python code in a fresh process.check=TrueraisesCalledProcessErrorwhen the return code is not 0, so a failure cannot go unnoticed.- If the program does not exist at all, you get
FileNotFoundError.
Input, Timeouts and Safety
import subprocess
import sys
# Send text to a program's standard input
r = subprocess.run(["sort"], input="Sylhet\nDhaka\nKhulna\n", capture_output=True, text=True)
print(r.stdout.split())
# timeout stops a program that runs too long
try:
subprocess.run([sys.executable, "-c", "import time; time.sleep(5)"], timeout=0.5)
except subprocess.TimeoutExpired as e:
print("TimeoutExpired after", e.timeout, "seconds")
# Pass user input as a list item, never by building a shell string
filename = "report.txt; rm notes.txt" # a dangerous "file name"
r = subprocess.run(["echo", "Looking for", filename], capture_output=True, text=True)
print(r.stdout.strip()) # printed as plain text, nothing was deleted
# Extra environment variables for the child process
import os
env = {**os.environ, "APP_MODE": "test"}
r = subprocess.run([sys.executable, "-c", "import os; print(os.environ['APP_MODE'])"],
capture_output=True, text=True, env=env)
print("child saw APP_MODE =", r.stdout.strip())
# Popen: read output line by line while the program runs
code = "for i in range(3): print('step', i, flush=True)"
with subprocess.Popen([sys.executable, "-c", code], stdout=subprocess.PIPE, text=True) as p:
for line in p.stdout:
print("got:", line.strip())
print("exit code:", p.returncode)
Output
['Dhaka', 'Khulna', 'Sylhet']
TimeoutExpired after 0.5 seconds
Looking for report.txt; rm notes.txt
child saw APP_MODE = test
got: step 0
got: step 1
got: step 2
exit code: 0
input=sends text to the program as if it were typed in. Heresortreceives three city names and sorts them.timeout=0.5stops a program that runs longer than half a second and raisesTimeoutExpired. Always set a timeout for programs that might hang.- The file name contains
; rm notes.txt. Because it is passed as one list item,echojust prints it. No shell reads it, so thermpart never runs. env=sets the environment variables the child program sees. Copyos.environfirst so the usual ones, such asPATH, are still there.Popenstarts a program and lets you read its output while it runs, line by line.runwaits until the end.
Why Not shell=True?
With shell=True you pass one string, and a shell (like bash or cmd) reads it. The shell treats characters such as ;, &&, | and $ as commands. If any part of that string comes from a user, they can add their own command. This is called command injection, and it is a serious security hole.
| Unsafe | Safe |
|---|---|
run(f"ls {folder}", shell=True) | run(["ls", folder]) |
run("cat a.txt | sort", shell=True) | Read the file in Python, or pass input= to run(["sort"]) |
Use shell=True only with fixed strings you wrote yourself, never with outside input.
Common Mistakes
- Passing one string without
shell=True, such asrun("ls -l"). Python looks for a program literally named “ls -l”. Split it:["ls", "-l"]. - Ignoring the return code. A failed command does not raise an error unless you use
check=True. - Forgetting
text=True, then comparing bytes likeb"ok\n"with the string"ok". - No timeout on a program that waits for input, which makes your script hang forever.
Practice Exercises
Exercise 1. Run Python in a subprocess to print 2 ** 10, and store the result as an int.
Show answer
import subprocess, sys
r = subprocess.run([sys.executable, "-c", "print(2 ** 10)"],
capture_output=True, text=True, check=True)
value = int(r.stdout)
print(value + 1) # 1025
int() ignores the newline at the end of the output.
Exercise 2. A user types a folder name into your program. Which of these is safe: run("ls " + name, shell=True) or run(["ls", name])?
Show answer
The second. A list item is passed straight to ls as one argument, so characters like ; have no special meaning.
Frequently Asked Questions
What is the difference between subprocess and os.system?
os.system is older. It always uses a shell, cannot capture output easily and only returns a status number. subprocess.run is safer and gives you the output, errors, timeouts and input. Prefer subprocess.
Should I use subprocess for things Python can do itself?
Usually not. Copying files, listing folders or sorting text is faster, safer and works on every system when done in Python, with modules such as shutil and pathlib. Use subprocess for real external programs such as Git or FFmpeg.
Summary
subprocess.run([...], capture_output=True, text=True)runs a program and collects its output.- Return code 0 means success;
check=Trueturns failures into exceptions. - Use
timeout,inputandenvto control the program. - Pass commands as lists and avoid
shell=Truewith outside input.
