How to Execute a Program or System Command in Python

Avatar

By squashlabs, Last Updated: November 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

Related Article: How to Suppress Python Warnings

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

How to Measure Elapsed Time in Python

Measuring elapsed time in Python is essential for many programming tasks. This guide provides simple code examples using the time module and the datetime module.... read more

How to Execute a Curl Command Using Python

Executing a curl command in Python can be a powerful tool for interacting with APIs and sending HTTP requests. This article provides a guide on how to execute a curl... read more

How to Parse a YAML File in Python

Parsing YAML files in Python can be made easy with the help of Python's yaml parser. This article provides a guide on how to parse YAML files using the PyYAML and... read more

How to Automatically Create a Requirements.txt in Python

Managing dependencies in Python is crucial for smooth software development. In this article, we will explore two methods to automatically create a requirements.txt file,... read more

How to Pretty Print a JSON File in Python (Human Readable)

Prettyprinting a JSON file in Python is a common task for software engineers. This article provides a guide on how to achieve this using the dump() and dumps()... read more

How to Manage Memory with Python

Python memory management is a fundamental aspect of programming. This article provides an overview of memory allocation and deallocation in Python, covering topics such... read more