Introduction
Subprocess allows spawning external processes and interacting with system commands.
Basic Execution
import subprocess
# Run command
result = subprocess.run(["ls", "-la"], capture_output=True, text=True)
print(result.stdout)
print(result.stderr)
# Shell command
result = subprocess.run("ls -la", shell=True, capture_output=True)
Working with Output
import subprocess
# Get output as string
result = subprocess.run(["python", "--version"], capture_output=True, text=True)
print(result.stdout)
# Check return code
result = subprocess.run(["ls", "nonexistent"])
print(result.returncode) # 2
# Raise on non-zero exit
try:
subprocess.run(["ls"], check=True)
except subprocess.CalledProcessError as e:
print(f"Command failed: {e}")
Async Execution
import subprocess
# Popen for async
process = subprocess.Popen(["python", "-c", "import time; time.sleep(5)"])
process.wait() # Wait for completion
process.terminate() # Kill process
Practice Problems
- Run system commands from Python
- Capture command output
- Handle command errors
- Use Popen for async processes
- Pipe commands together