Python subprocess Module Explained 🧩

Terminal command icon

Python subprocess Module Explained 🧩

The subprocess module allows Python scripts to run external commands, scripts, or programs, capturing their output and managing their execution easily and efficiently.

1. Basic Execution with `subprocess.run()`

import subprocess

result = subprocess.run(['echo', 'Hello World'], capture_output=True, text=True)
print(result.stdout)  # Hello World

2. Checking Errors and Return Codes

import subprocess

res = subprocess.run(['ls', 'non_existent_folder'], capture_output=True, text=True)
if res.returncode != 0:
    print("Error:", res.stderr)
else:
    print(res.stdout)

3. Sending Input and Reading Output

import subprocess

p = subprocess.run(['grep', 'hello'], input='hello world\nhi python', capture_output=True, text=True)
print(p.stdout)  # hello world

4. Asynchronous Execution with `Popen`

import subprocess

p = subprocess.Popen(['ping', '-c', '3', 'google.com'], stdout=subprocess.PIPE, text=True)
for line in p.stdout:
    print(line.strip())
p.wait()
print("Exit code:", p.returncode)

Summary

  • Execute external commands and capture outputs easily using subprocess.run().
  • Check for errors using return codes and stderr.
  • Provide input to commands via the input parameter.
  • Use Popen for asynchronous execution or real-time output handling.

Comments

Popular posts from this blog

Mastering Python Generators and yield: Efficient Iteration Explained

Mastering Python Sets: Remove Duplicates and Do More

Python Logging Module: Basics and Best Practices 📝