← Back to Articles
Tutorial

Run Shell Commands in Python Easily

Learn how to execute shell commands in Python using subprocess for automation.

Python offers powerful capabilities for automating tasks, including running shell commands directly from your scripts. This can be incredibly useful for system administration, data processing, and more.

To run shell commands in Python, you can use the 'subprocess' module. This module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. Here's a basic example using subprocess.run() to execute a shell command.

When running shell commands in Python, always ensure that your commands are constructed safely to avoid shell injection vulnerabilities. Using subprocess.run() with a list of arguments rather than a single string is a good practice.

A common mistake when running shell commands in Python is neglecting to handle exceptions or errors that may occur during execution. Always check the return code and handle exceptions to make your code robust.

Code Examples

Example 1

import subprocess
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(result.stdout)

Example 2

import subprocess
try:
    result = subprocess.run(['mkdir', 'new_folder'], check=True)
except subprocess.CalledProcessError as e:
    print(f'Error: {e}')

More Python Tutorials