Sub topic 1
Running External Commands from Python with subprocess
Prerequisites
This chapter assumes basic Python syntax, exceptions, and terminal use. You should know that a process communicates through standard input, standard output, and standard error.
Why use subprocess instead of os.system
os.system() runs a command through the operating system's shell and returns only its exit status. It gives you little control over arguments, output, errors, or time limits.
The subprocess module provides those controls. Its usual entry point, subprocess.run(), starts a child process, waits for it, and returns a CompletedProcess object.
Your first command with subprocess.run
Pass the program and its arguments as a list. sys.executable identifies the current Python interpreter, so this example works across operating systems.
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)text=True decodes output into strings. Without it, output is returned as bytes. check=True raises CalledProcessError when the child exits unsuccessfully.
Passing arguments: lists, strings and shell=True
A list keeps each argument separate. This prevents spaces and shell characters inside a value from changing the command.
import subprocess
filename = "report; echo unexpected"
subprocess.run(["cat", filename], check=True)With shell=True, Python sends a command string to a shell. That is sometimes needed for shell features such as wildcard expansion or pipes, but interpolating untrusted text can cause shell injection.
If you have a trusted command string, shlex.split() can turn it into an argument list while respecting quoted spaces:
import shlex
print(shlex.split("ls -l 'my folder'"))Capturing output as text or bytes
Use capture_output=True to collect both standard output and standard error. Use encoding when the child uses a known character encoding.
import subprocess
import sys
result = subprocess.run(
[sys.executable, "-c", "print('done')"],
capture_output=True,
text=True,
encoding="utf-8",
)
print("stdout:", result.stdout.strip())
print("stderr:", result.stderr)Without text=True, result.stdout and result.stderr are byte strings, such as b"done\n". Bytes are useful when output is not text or must be decoded manually.
Exercise
Which form should you use when a filename comes from a user: subprocess.run(["cat", filename]) or subprocess.run(f"cat {filename}", shell=True)?
Show answer
Use the list form. It passes the filename as one argument and avoids shell interpretation.