To run an external command from a Python script and capture its output, you can use the subprocess
module. The subprocess
module provides a convenient and flexible way to interact with the shell and run shell commands from your Python code.
Here’s an example of how to run a shell command and capture its output:
import subprocess
# Run a shell command and capture its output
result = subprocess.run(['ls', '-l', '/'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Print the command's output
print(result.stdout.decode())
In the above example, we run the ls
command with the -l
option and the directory /
, and capture its standard output and standard error output in the result
object. The stdout
attribute of the result
object contains the standard output of the command, which we decode into a string and print to the console.
You can also run a command and store its output in a variable, like this:
import subprocess
# Run a shell command and capture its output
output = subprocess.check_output(['ls', '-l', '/'])
# Store the output in a variable
output = output.decode()
# Print the output
print(output)
In this example, we use the check_output
function to run the command and capture its output, and store the output in the output
variable. We then decode the output from a bytes object to a string and print it to the console.