2 min read

Python Subprocess Module

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. It is the recommended way to execute system commands and other programs from Python.

Importing the Module

import subprocess

Running Commands

The subprocess.run() function is the primary entry point for running commands.

Basic Usage

import subprocess

# Run a command and wait for it to finish
subprocess.run(["ls", "-l"])

Capturing Output

To capture the output of a command (stdout) so you can use it in your script, use capture_output=True and text=True (to get strings instead of bytes).

result = subprocess.run(["echo", "Hello World"], capture_output=True, text=True)

print("Stdout:", result.stdout)
print("Return Code:", result.returncode)

Checking for Errors

If you want the script to raise an exception if the command fails (returns a non-zero exit code), use check=True.

try:
    subprocess.run(["ls", "non_existent_file"], check=True)
except subprocess.CalledProcessError as e:
    print(f"Command failed with return code {e.returncode}")

Popen Constructor

For more advanced use cases (like interacting with a process while it is running), you can use the underlying Popen class.

process = subprocess.Popen(["ping", "127.0.0.1"], stdout=subprocess.PIPE, text=True)

# Read line by line as it comes in
for line in process.stdout:
    print(f"Output: {line.strip()}")

programming/python/python