Use subprocess.run(["cmd", "arg1"], capture_output=True, text=True, check=True) to execute an external command safely and read its standard output via result.stdout and standard error via result.stderr—avoiding os.system() (which cannot capture output) and avoiding shell=True unless shell features like pipes or wildcards are strictly required.
Basic Example
import subprocess
# 1. Recommended: Pass command and arguments as a list with capture_output=True & text=True
result = subprocess.run(
["python3", "--version"],
capture_output=True, # Captures both stdout and stderr
text=True, # Decodes bytes to str automatically (alias for encoding="utf-8")
check=True, # Raises CalledProcessError if exit code != 0
)
print("Exit code:", result.returncode) # Output: 0
print("Stdout:", result.stdout.strip()) # Output: Python 3.x.x
print("Stderr:", result.stderr.strip()) # Output: (empty)
Key Details & Edge Cases
- Pass arguments as a
list[str]withoutshell=True(Security & Quoting):- Passing a list (
["grep", "-rn", "my pattern", "./src"]) invokes the executable directly without spawning/bin/shorcmd.exe, preventing shell injection vulnerabilities when filenames or variables contain spaces, quotes, or metacharacters (;,|,$()). - Use
shell=True(with a single command string, e.g.,subprocess.run("ls -la | grep .py", shell=True, capture_output=True, text=True)) only when you explicitly need shell pipelines, redirection (), or glob expansion—and sanitize untrusted inputs withshutil.which()orshlex.quote().
- Passing a list (
- Error handling (
check=Truevs. inspectingreturncode):- With
check=True, any non-zero exit status raisessubprocess.CalledProcessError, exposingerr.returncode,err.stdout, anderr.stderr:try: res = subprocess.run(["ls", "/nonexistent"], capture_output=True, text=True, check=True) except subprocess.CalledProcessError as err: print(f"Command failed ({err.returncode}): {err.stderr.strip()}") - Without
check=True(defaultcheck=False),subprocess.run()returns normally even when the command fails; always checkif result.returncode != 0:before trustingresult.stdout.
- With
- Setting timeouts and working directories (
timeout,cwd,env):- Pass
timeout=10(in seconds) to abort hanging subprocesses withsubprocess.TimeoutExpired. - Pass
cwd="/path/to/dir"to run the command inside a specific directory without callingos.chdir().
- Pass
- Combining
stdoutandstderrinto a single stream: If you want interleaved standard output and error output in exact chronological order, omitcapture_output=Trueand passstdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True. - Streaming real-time output line-by-line (
subprocess.Popen):subprocess.run()buffers all output in memory until the command exits. For long-running commands (likedocker buildorpytest) where you need live line-by-line output while capturing it, iterate overPopen.stdout:lines = [] with subprocess.Popen( ["ping", "-c", "3", "127.0.0.1"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, ) as proc: for line in proc.stdout: print(line, end="") # Stream live to console lines.append(line)
You must log in or register to comment.
