Course contentsShow
← Python
Lesson 722 of 1,06011. Standard Library EssentialsFree lesson

Executing External Shell Commands from Python

Learners will invoke and interact with external system utilities and shell commands directly from their Python scripts using the operating system interface.

In this lesson, you will learn how to bridge the gap between your Python scripts and your computer’s operating system by executing external shell commands directly.

The Power of Subprocesses

While Python is incredibly capable, there are times when you need to leverage the tools already installed on your machine—such as git, grep, or custom system utilities. Rather than rewriting these tools in Python, you can invoke them directly using the subprocess module. This module allows you to spawn new processes, connect to their input/output pipes, and obtain their return codes.

Running Simple Commands

The most straightforward way to run a command is using subprocess.run(). This function executes a command, waits for it to finish, and returns a CompletedProcess instance.

To avoid common security risks like shell injection, it is best practice to pass your command as a list of strings rather than a single string. Here is how you might list the contents of a directory using the system’s ls command:

import subprocess

# The command is passed as a list: ["command", "argument1", "argument2"]
result = subprocess.run(["ls", "-l"], capture_output=True, text=True)

# Accessing the output captured from the shell
print("Command output:")
print(result.stdout)

In this snippet:

  • capture_output=True tells Python to grab the standard output and error so you can inspect them later.
  • text=True ensures the output is returned as a readable string rather than raw bytes.

When to Use This

You should reach for this module when you need to integrate system-level operations into your workflow. Whether you are automating a backup script, interacting with version control, or parsing output from a legacy command-line tool, subprocess acts as the standard interface for "talking" to the shell from your Python code.

Always be cautious when executing commands, especially if any part of the command string is derived from user input. By using the list-based approach, Python handles the arguments safely, preventing the shell from misinterpreting your intentions.

Key Takeaway: The subprocess.run() function is the modern, recommended way to execute external commands safely by passing arguments as a list and capturing the resulting output for your Python program to process.