Andromeda
Note

Subprocess Module (Python)

Definition

A module that allows Python to launch and interact with other programs on the computer.

Why It Matters

The subprocess module is the primary tool for “system orchestration”; it allows Python to act as a meta-language that controls other software, enabling complex automations that leverage the specialized power of the entire operating system rather than just Python’s built-in libraries.

Core Concepts

  • The “Forking” Model: Creating a new process that runs independently of the Python script.
  • subprocess.Popen(): Launches the program (e.g., Popen(['notepad.exe', 'file.txt'])).
  • Control Methods:
    • .poll(): Returns None if the process is still running, or its exit code if finished.
    • .wait(): Blocks until the process finishes.
    • .terminate(): Forcefully closes the program.
  • Standard App Integration: Launching the default application for a file type using start (Windows), open (macOS), or xdg-open (Linux).
  • Example Usage:
import subprocess

# Launch Notepad (Windows) or TextEdit (macOS)
# Note: This will block until the program is closed if using .wait()
process = subprocess.Popen(['notepad.exe'])

# Check if it's still running
if process.poll() is None:
    print("Program is running...")

# Force close after some logic
process.terminate()

Connected Concepts