What You’ll Learn
In this lesson, you’ll learn how to use Python’s subprocess module to run external commands from an automation script without handing command construction to a shell.
- Run a command with arguments stored safely in a list.
- Capture standard output and standard error.
- Inspect an exit code to determine whether a command succeeded.
- Handle missing commands, timeouts, and other failures.
- Recognize why arbitrary strings and
shell=Truecan create security problems.
The Concept
Python programs often need to coordinate with existing command-line tools. An automation script might invoke a backup utility, inspect a Git repository, run a system diagnostic, or call a cloud command-line tool.
The subprocess.run() function starts an external process and waits for it to finish. Its first argument should usually be a list: the executable name followed by one item for each argument. This keeps argument boundaries clear and avoids asking a shell to interpret the command.
When a process finishes, it provides an exit code. By convention, 0 means success, while a nonzero value indicates failure. The process can also write to two streams:
- Standard output (
stdout) contains normal results. - Standard error (
stderr) contains diagnostics and error messages.
For automation, use options such as capture_output=True and text=True when you want to inspect command output as strings. A timeout prevents a command that hangs from holding up the entire script.
Basic Example
This script launches another Python process as a stand-in for an external utility. The same pattern works with commands such as git, a backup tool, or an operating-system diagnostic utility.
import subprocess
import sys
result = subprocess.run(
[
sys.executable,
"-c",
"print('backup preflight: ready')",
],
capture_output=True,
text=True,
check=False,
)
print(f"Exit code: {result.returncode}")
print(f"Output: {result.stdout.strip()}")
if result.stderr:
print(f"Error output: {result.stderr.strip()}")
if result.returncode == 0:
print("The external command succeeded.")
else:
print("The external command failed.")Expected Output
Exit code: 0
Output: backup preflight: ready
The external command succeeded.How the Code Works
sys.executable points to the Python interpreter running the current script. The -c argument tells that interpreter to execute the following string. This makes the example portable because it does not depend on whether a command named python or python3 is available on the system.
The list passed to subprocess.run() is equivalent to this command-line structure:
- Executable: the current Python interpreter
- Argument:
-c - Argument: the short Python program to execute
capture_output=True captures both output streams instead of immediately displaying them in the terminal. text=True decodes those streams into strings, so methods such as strip() can be used.
Because check=False is explicit, a nonzero exit code does not automatically raise an exception. The script can inspect result.returncode and decide whether to retry, log, or stop the automation.
For a command that must succeed, you can instead use check=True. In that case, Python raises subprocess.CalledProcessError when the command exits unsuccessfully. Use a try/except block when you choose that behavior.
Another Example
A deployment or maintenance script may want to check whether Git is available before collecting repository information. This example demonstrates a real utility, a timeout, and handling a missing executable.
import subprocess
def show_git_version():
try:
result = subprocess.run(
["git", "--version"],
capture_output=True,
text=True,
check=False,
timeout=5,
)
except FileNotFoundError:
print("Git is not installed or is not on PATH.")
return
except subprocess.TimeoutExpired:
print("Git did not respond within five seconds.")
return
if result.returncode == 0:
print(f"Detected: {result.stdout.strip()}")
else:
print("Git returned an error.")
if result.stderr:
print(result.stderr.strip())
show_git_version()The command is passed as ["git", "--version"], not as one string such as "git --version". This is both easier to reason about and safer when arguments come from configuration or user input.
This pattern is useful in preflight checks: the script can verify that a required utility exists and responds before beginning a larger automation task. If your script needs to execute cloud utilities, you can apply the same approach when you automate AWS CLI commands.
Common Mistakes
Building one command string from untrusted input
Concatenating user-controlled text into a command string can allow unexpected commands or arguments to be interpreted. Prefer a list of arguments:
import subprocess
filename = "weekly report.txt"
result = subprocess.run(
["cat", filename],
capture_output=True,
text=True,
check=False,
)The list form passes the filename as one argument, including its space. It does not require manual quoting.
Using shell=True without a strong reason
shell=True asks the operating system to run a shell command. Shell features such as pipes and wildcard expansion can be useful in carefully controlled cases, but they also create injection risks when any part of the command is influenced by outside input. For ordinary command execution, leave shell at its default value of False.
Ignoring the exit code
A command can produce output and still fail. Always inspect returncode, use check=True, or otherwise define how the automation should respond to failure.
Allowing a process to wait forever
Network tools, prompts, locks, and broken utilities can cause a subprocess to hang. Set a reasonable timeout for operations that should finish within a known period, and handle subprocess.TimeoutExpired.
Also be careful about logging captured output. Command output can contain tokens, file contents, or other sensitive values. Avoid printing secrets and consider guidance on how to protect secrets from command output.
Try It Yourself
Write a function named run_preflight() that runs a child Python process with sys.executable. Have the child print disk check: passed, capture its output, and print either the captured message or a failure message based on the exit code.
Use a list of arguments, capture_output=True, text=True, and check=False. Then modify the child command so it exits with a nonzero status and observe how your function responds.
Challenge
Create a reusable function called run_command(command, timeout=10) with these requirements:
- Accept a list of command arguments.
- Return a dictionary containing
returncode,stdout, andstderrwhen the command starts successfully. - Return a useful error dictionary when the executable is missing.
- Return a useful error dictionary when the command exceeds the timeout.
- Capture output as text without using
shell=True.
Test the function with a child Python process that prints a short status message. Also test it with an executable name that is unlikely to exist, such as command-that-does-not-exist.
Solution
import subprocess
import sys
def run_command(command, timeout=10):
try:
result = subprocess.run(
command,
capture_output=True,
text=True,
check=False,
timeout=timeout,
)
except FileNotFoundError:
return {
"returncode": None,
"stdout": "",
"stderr": f"Executable not found: {command[0]}",
}
except subprocess.TimeoutExpired:
return {
"returncode": None,
"stdout": "",
"stderr": f"Command timed out after {timeout} seconds.",
}
return {
"returncode": result.returncode,
"stdout": result.stdout.strip(),
"stderr": result.stderr.strip(),
}
successful_check = run_command(
[
sys.executable,
"-c",
"print('configuration check: passed')",
]
)
print(successful_check)
missing_command = run_command(["command-that-does-not-exist"])
print(missing_command)The function keeps command execution in one place and gives callers a consistent dictionary to inspect. It does not treat every nonzero exit code as a Python exception, so the caller can decide what each result means. Missing executables and timeouts are handled separately because they indicate that the process could not complete normally.
Key Takeaways
- Use
subprocess.run()to execute external commands and wait for their results. - Prefer a list of arguments and keep
shell=Falsefor ordinary command execution. - Capture
stdoutandstderrwhen an automation script needs to inspect or log results. - Check
returncode, or usecheck=Truewith exception handling. - Use timeouts and avoid exposing sensitive captured output in logs.



