Python Run External Command And Get Output On Screen or In Variable

https‮‬://www.lautturi.com
Python Run External Command And Get Output On Screen or In Variable

To run an external command and get the output in Python, you can use the subprocess module and the subprocess.check_output() function. The subprocess.check_output() function runs a command and returns the output as a byte string.

Here's an example of how to use the subprocess.check_output() function to run an external command and get the output in Python:

import subprocess

# Run an external command and get the output
output = subprocess.check_output(["ls", "-l"])
print(output)

This will run the ls command with the -l flag, which lists the contents of the current directory in a long format, and print the output.

It's important to note that the subprocess.check_output() function returns the output as a byte string, so if you want to print the output as a string, you will need to decode the byte string. For example:

import subprocess

# Run an external command and get the output as a string
output = subprocess.check_output(["ls", "-l"]).decode("utf-8")
print(output)

You can also use the subprocess.run() function to run an external command and get the output in Python. The subprocess.run() function returns a CompletedProcess object that contains the return code, stdout, and stderr of the command.

Here's an example of how to use the subprocess.run() function to run an external command and get the output in Python:

import subprocess

# Run an external command and get the output
result = subprocess.run(["ls", "-l"], capture_output=True)
print(result.stdout)

This will run the ls command with the -l flag and print the output.

It's important to note that the subprocess module has a number of other functions and features that you can use to run external commands and get the output in Python. Consult the subprocess documentation and online resources for more information on how to use this module to run commands and get the output in Python.

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