pythonbeginner

Run Shell Commands with subprocess

Execute external commands safely using subprocess.run in Python.

python
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.