pythonbeginner
Run Shell Commands with subprocess
Execute external commands safely using subprocess.run in Python.
pythonPress ⌘/Ctrl + Shift + C to copy
import subprocess
# Simple command
result = subprocess.run(
["ls", "-la"],
capture_output=True,
text=True,
check=True
)
print(result.stdout)
# Command with timeout
try:
result = subprocess.run(
["ping", "-c", "3", "google.com"],
capture_output=True,
text=True,
timeout=10
)
print(result.stdout)
except subprocess.TimeoutExpired:
print("Command timed out")
except subprocess.CalledProcessError as e:
print(f"Command failed: {e.stderr}")
# Pipe commands
ps = subprocess.run(["ps", "aux"], capture_output=True, text=True)
grep = subprocess.run(
["grep", "python"],
input=ps.stdout,
capture_output=True,
text=True
)
print(grep.stdout)Use Cases
- Automation scripts
- CI/CD helpers
- System administration
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonadvanced
Subprocess Execution
Advanced Python pattern: subprocess-execution
Best for: advanced programming
#python#advanced
pythonbeginner
Dataclass with Validation
Python dataclass with __post_init__ field validation, type coercion, and descriptive error messages.
Best for: Data transfer objects
#dataclass#validation
pythonintermediate
Custom Context Manager
Context managers for resource management using both class-based and decorator approaches with error handling.
Best for: Database connection management
#context-manager#resource-management
pythonintermediate
Pytest Fixtures and Parametrize
Reusable pytest fixtures with scope control, parametrize for data-driven tests, and temporary resources.
Best for: Unit test setup
#pytest#testing