← Back to Python

All Topics

Advertisement

Learn/Python/Advanced Python

Subprocess

Topic: System

Advertisement

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

  1. Run system commands from Python
  2. Capture command output
  3. Handle command errors
  4. Use Popen for async processes
  5. Pipe commands together

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →