Mastering Python’s subprocess.run: Tips, Parameters, and Best Practices
Learn how to effectively use Python 3’s subprocess.run() function—including the powerful check=True option—to execute system commands, capture output, handle errors, and leverage key parameters such as stdout, stderr, text, and capture_output, with practical code examples and best‑practice guidelines.
Overview
The subprocess.run() function is a modern, powerful way to execute external programs or system commands from Python 3, replacing older approaches like os.system(). It allows developers to run commands, capture their output, and handle return codes in a safe and flexible manner.
Key Parameters
command: A string or list representing the command to execute. Using a list (e.g., ['ls', '-l']) avoids shell‑injection risks. check: Boolean, default False. When set to True, a non‑zero exit status raises subprocess.CalledProcessError, enabling explicit error handling. stdout and stderr: Define how standard output and error are handled. Setting them to subprocess.PIPE captures the streams. text: When True, output is decoded to a string instead of bytes. capture_output: Shortcut that sets both stdout and stderr to subprocess.PIPE.
Basic Example
import subprocess
try:
result = subprocess.run(['ls', '-l'], check=True, text=True, capture_output=True)
print("Standard output:", result.stdout)
except subprocess.CalledProcessError as e:
print("Command failed, return code:", e.returncode)
print("Error output:", e.stderr)This snippet demonstrates executing ls -l, automatically raising an exception on failure, and printing captured output.
Handling Execution Status
Capture return code
result = subprocess.run(['ls', '-l'], text=True, capture_output=True)
if result.returncode == 0:
print("Command succeeded")
else:
print("Command failed, return code:", result.returncode)Use check=True for exception handling
try:
subprocess.run(['false'], check=True)
except subprocess.CalledProcessError as e:
print(f"Command failed, error code: {e.returncode}")Capture output
result = subprocess.run(['echo', 'Hello, World!'], text=True, capture_output=True)
print("Standard output:", result.stdout)Process standard error
try:
subprocess.run(['ls', '/nonexistent'], check=True, text=True, capture_output=True)
except subprocess.CalledProcessError as e:
print("Error output:", e.stderr)The CompletedProcess Object
The object returned by subprocess.run() contains several useful attributes: args: The command that was executed. returncode: Exit status (0 for success, non‑zero for failure). stdout: Captured standard output (if requested). stderr: Captured standard error (if requested).
result = subprocess.run(['echo', 'Python subprocess module!'], text=True, capture_output=True)
print("Command:", result.args)
print("Return code:", result.returncode)
print("Standard output:", result.stdout)Conclusion and Best Practices
Using subprocess.run() enables robust interaction with system commands. Recommended practices include:
Prefer passing the command as a list to avoid shell injection.
Combine check=True with try…except to handle failures explicitly.
Capture output with capture_output=True or by setting stdout / stderr to subprocess.PIPE for further processing.
Following these guidelines helps you write safer, more maintainable Python scripts that effectively manage external processes.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Ops Development & AI Practice
DevSecOps engineer sharing experiences and insights on AI, Web3, and Claude code development. Aims to help solve technical challenges, improve development efficiency, and grow through community interaction. Feel free to comment and discuss.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
