In Python, the subprocess
module provides a way to create new processes, interact with them, and retrieve their output. One useful function in this module is subprocess.check_output()
, which allows you to capture the output of a command executed in a subprocess.
The check_output()
Function
The check_output()
function is a convenience method to run a command and capture its standard output as a byte string. It takes a single argument, which is the command to be executed, and returns the output as a byte string.
import subprocess
output = subprocess.check_output(["ls", "-l"])
print(output)
In the code above, subprocess.check_output(["ls", "-l"])
executes the ls -l
command in a subprocess and captures its output. The output is then printed using the print()
function.
Capturing Output as a String
By default, check_output()
returns the output as a byte string. If you want to capture the output as a regular string, you can specify the encoding
parameter.
import subprocess
output = subprocess.check_output(["ls", "-l"], encoding="utf-8")
print(output)
In this example, output
will be a string representing the output of the ls -l
command.
Handling Command Execution Errors
If the command executed by check_output()
returns a non-zero exit status, a CalledProcessError
exception is raised. You can catch this exception and handle the error accordingly.
import subprocess
try:
output = subprocess.check_output(["invalid_command"])
except subprocess.CalledProcessError as e:
print(f"Command execution failed with return code {e.returncode}.")
In this case, the invalid_command
will raise a CalledProcessError
, and the error message will be printed.
Conclusion
The subprocess.check_output()
function provides a convenient way to execute commands in a subprocess and capture their output. It is a powerful tool for running external commands from within your Python scripts and automating various tasks.