How to Execute a Program or System Command in Python

Avatar

By squashlabs, Last Updated: Nov. 26, 2023

How to Execute a Program or System Command in Python

To execute a program or system command in Python, you can make use of the subprocess module. The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. Here are two possible ways to execute a program or system command in Python:

Using the subprocess.run() function

The subprocess.run() function is a high-level function that simplifies the process of executing a program or system command in Python. It allows you to execute a command and wait for it to complete. Here's how you can use it:

import subprocess

# Execute a command and wait for it to complete
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)

# Print the output of the command
print(result.stdout)

In the above example, we use the subprocess.run() function to execute the ls -l command, which lists the files and directories in the current directory. The capture_output=True argument tells subprocess.run() to capture the output of the command, and the text=True argument specifies that the output should be returned as a string.

Related Article: How to Use Python with Multiple Languages (Locale Guide)

Using the subprocess.Popen() class

The subprocess.Popen() class provides a more flexible way to execute a program or system command in Python. It allows you to spawn a new process, connect to its input/output/error pipes, and interact with it programmatically. Here's an example:

import subprocess

# Execute a command and capture its output
process = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
stdout, stderr = process.communicate()

# Print the output of the command
print(stdout)

In the above example, we use the subprocess.Popen() class to execute the ls -l command. We specify stdout=subprocess.PIPE to capture the standard output of the command, and stderr=subprocess.PIPE to capture any error output. We then use the communicate() method to read the output of the command.

Best practices

When executing a program or system command in Python, it's important to keep the following best practices in mind:

- Use the subprocess.run() function for simple cases where you just need to execute a command and wait for it to complete.

- Use the subprocess.Popen() class for more complex cases where you need to interact with the process programmatically or handle its input/output/error pipes.

- Always specify the full path to the command you want to execute, or ensure that the command is available in the system's PATH environment variable. This helps avoid issues with command not found errors.

- Handle any error output or return codes from the command appropriately. You can check the return code of a command by accessing the returncode attribute of the subprocess.CompletedProcess object returned by subprocess.run().

- Avoid using the shell=True argument with subprocess.run() or subprocess.Popen(), as it can introduce security vulnerabilities if the command includes user-supplied input.

Alternative ideas

Apart from the subprocess module, there are other ways to execute a program or system command in Python. Some alternatives include:

- The os.system() function: This function allows you to execute a command in a subshell and wait for it to complete. However, it is generally recommended to use the subprocess module instead, as it provides more flexibility and control.

- The os.popen() function: This function allows you to execute a command and obtain a file-like object that you can use to read its output. However, it is considered deprecated and should be avoided in favor of the subprocess module.

Overall, the subprocess module provides a comprehensive and reliable way to execute programs or system commands in Python, and is the recommended approach in most cases.

For more information on the subprocess module, you can refer to the official Python documentation: https://docs.python.org/3/library/subprocess.html

More Articles from the Python Tutorial: From Basics to Advanced Concepts series:

What are The Most Popular Data Structures in Python?

This article examines the most popular data structures used in Python programming. It provides an overview of various data structures such as lists, … read more

How To Check If List Is Empty In Python

Determining if a list is empty in Python can be achieved using simple code examples. Two common methods are using the len() function and the not oper… read more

How to End Python Programs

This guide provides software developers with essential information on correctly terminating Python programs. It covers various methods for ending Pyt… read more

Tutorial on Python Generators and the Yield Keyword

Python generators and the yield keyword are powerful tools for creating and memory-friendly code. This detailed guide explores their implementation, … read more

Implementing Security Practices in Django

User authentication, security hardening, and custom user models are essential components of any Django application. This article explores various sec… read more

How to Use the IsAlpha Function in Python

This article provides a detailed guide on the usage and applications of the isalpha function in Python programming. It covers the overview of the isa… read more

16 Amazing Python Libraries You Can Use Now

In this article, we will introduce you to 16 amazing Python libraries that are widely used by top software teams. These libraries are powerful tools … read more

How to Flatten a List of Lists in Python

Learn how to flatten a list of lists in Python using two simple methods: nested list comprehensions and itertools.chain.from_iterable(). Discover the… read more

PHP vs Python: How to Choose the Right Language

Choosing the right programming language for your project is crucial. In this article, we compare PHP and Python, helping you make an informed decisio… read more

How To Install Packages With Pip From Requirements.Txt

Installing packages with pip from requirements.txt is a common task for Python developers. In this article, you will learn how to efficiently use pip… read more