How to Run Linux Commands in Python?

Estimated read time 2 min read

To run Linux commands in Python, you can use the subprocess module, which provides a way to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. Here’s an example:

import subprocess

# Run a Linux command
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)

# Print the command output
print(result.stdout)

In this example, we use the subprocess.run() function to execute the ls -l command, which lists the files and directories in the current directory in long format. We pass the command as a list of strings, where the first element is the command name (ls) and the subsequent elements are its arguments (-l).

The capture_output=True argument captures the output of the command, and the text=True argument ensures that the output is returned as a string rather than bytes.

The result of running the command is stored in the result object, which contains various attributes including stdout (standard output), stderr (standard error), and returncode (the return code of the command).

In this example, we print the standard output of the command using result.stdout.

You can modify the command and arguments as per your requirements. The subprocess module provides several other functions and options to control the execution and handling of the command’s input, output, and errors.

Note that when executing Linux commands in Python, you should exercise caution, especially when running commands that involve user input or that can modify the system. It’s important to validate and sanitize the command and its arguments to prevent any security vulnerabilities.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply