The subprocess
module in Python provides functionality for spawning new processes, connecting to their input/output/error pipes, and obtaining their return codes. One of the most commonly used functions in this module is subprocess.run()
.
What is subprocess.run()?
subprocess.run()
is a high-level method that combines the functionality of subprocess.Popen()
and subprocess.communicate()
into a single convenient call. It allows you to execute a command in the shell and wait for it to complete, capturing its output and return code.
Basic Usage
Here’s a basic example of how to use subprocess.run()
:
import subprocess
# Run a command and wait for it to complete
result = subprocess.run(["ls", "-l"], capture_output=True, text=True)
# Print the command's return code
print("Return code:", result.returncode)
# Print the command's output
print("Output:\n", result.stdout)
In this example, we are using subprocess.run()
to run the ls -l
command, which lists the contents of a directory in long format. The capture_output=True
argument tells subprocess.run()
to capture the command’s output, and text=True
specifies that the output should be decoded as a string.
We then access the command’s return code using result.returncode
and the output using result.stdout
. You can also access the error output using result.stderr
.
Input and Output
By default, subprocess.run()
does not capture the command’s input. However, you can pass the input using the input
parameter:
import subprocess
# Run a command with input
result = subprocess.run(["grep", "apple"], capture_output=True, text=True, input="apple\nbanana\ncarrot\n")
# Print the command's output
print("Output:\n", result.stdout)
In this example, we are using subprocess.run()
to run the grep
command, which searches for the keyword “apple” in the input. We pass the input using the input
parameter, which takes a string.
Error Handling
When subprocess.run()
encounters an error, it raises a subprocess.CalledProcessError
exception. You can catch this exception to handle errors gracefully:
import subprocess
try:
# Run a command and handle errors
subprocess.run(["nonexistent_command"], check=True)
except subprocess.CalledProcessError as e:
print("Command failed with return code", e.returncode)
print("Error output:", e.stderr)
In this example, we are attempting to run a nonexistent command, which will raise a CalledProcessError
. We catch the exception and print the return code and error output.
Conclusion
subprocess.run()
is a powerful and convenient function in Python for executing shell commands and capturing their output. By understanding its basic usage and options, you can easily integrate shell commands into your Python programs.
Remember to import the subprocess
module at the beginning of your script before using subprocess.run()
.