Python Execute Unix / Linux Command Examples

ht‮‬tps://www.lautturi.com
Python Execute Unix / Linux Command Examples

To execute Unix or Linux commands in Python, you can use the subprocess module and the subprocess.call() function. The subprocess.call() function takes a list of strings as an argument, where each string represents a command and its arguments.

Here's an example of how to use the subprocess.call() function to execute a Unix or Linux command in Python:

import subprocess

# Execute a Unix or Linux command
subprocess.call(["ls", "-l"])

In this example, the ls command is executed with the -l flag, which displays the contents of the current directory in a long format.

You can also use the subprocess.call() function to execute multiple commands in a single call. For example:

import subprocess

# Execute multiple Unix or Linux commands
subprocess.call(["ls", "-l"])
subprocess.call(["grep", "test"])

In this example, the ls command is executed first, followed by the grep command.

It's important to note that the subprocess.call() function will return the exit status of the command, which is a numerical value that indicates the success or failure of the command. A return value of 0 indicates success, while a non-zero return value indicates an error.

You can use the subprocess.check_output() function to capture the output of a command as a string. For example:

import subprocess

# Capture the output of a Unix or Linux command as a string
output = subprocess.check_output(["ls", "-l"])
print(output)

This will print the output of the ls command as a string.

It's also important to note that the subprocess module has a number of other functions and features that you can use to execute Unix or Linux commands in Python. Consult the subprocess documentation and online resources for more information on how to use this module to execute commands in Python.

Created Time:2017-10-30 14:27:12  Author:lautturi