Table of Contents

import subprocess

import subprocess is a Python import that runs external programs and captures their output. Use subprocess.run() to execute commands from Python.

Example

# Python
# description: run external commands, capture output
 
import subprocess
 
# Run command and capture output
result = subprocess.run(["ls", "-la"], capture_output=True, text=True)
print(result.stdout)
print(f"Exit code: {result.returncode}")
 
# Run with input/output pipes
result = subprocess.run(["grep", "error"], input="line 1\nerror line\nline 3\n", 
                        capture_output=True, text=True)
print(result.stdout)
 
# Check if command succeeded
result = subprocess.run(["python", "--version"], capture_output=True, text=True)
if result.returncode == 0:
    print(f"Success: {result.stdout.strip()}")
 
# Run shell command (less secure, use with caution)
result = subprocess.run("ps aux | grep python", shell=True, capture_output=True, text=True)
print(result.stdout)

Common functions