snippetpythonModeratepending
Python subprocess — safe command execution patterns
Viewed 0 times
subprocessruncheck_outputPopenshell commandsafe execution
python
Problem
Need to run external commands from Python safely. Using shell=True or legacy functions is dangerous with user input and makes error handling difficult.
Solution
Use subprocess.run with a list of arguments (no shell=True). Capture output, check return codes, and handle timeouts properly.
Code Snippets
Safe subprocess usage patterns
import subprocess
from pathlib import Path
# Basic: run and check exit code
result = subprocess.run(
['git', 'status', '--porcelain'],
capture_output=True, text=True, check=True,
cwd=Path.home() / 'project'
)
changed_files = result.stdout.splitlines()
# With timeout and error handling
try:
result = subprocess.run(
['ffmpeg', '-i', input_file, output_file],
capture_output=True, text=True,
timeout=300 # 5 minute timeout
)
if result.returncode != 0:
print(f'stderr: {result.stderr}')
except subprocess.TimeoutExpired:
print('Command timed out')
except FileNotFoundError:
print('ffmpeg not installed')
# NEVER do this with untrusted input:
# subprocess.run(f'echo {user_input}', shell=True) # DANGEROUS
# Instead, always pass args as a listRevisions (0)
No revisions yet.