In this tutorial, we will learn how to get the output of a subprocess in Python. The subprocess module allows us to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several other modules and functions, such as os.system()
, os.spawn*
, and many others.
Let’s go through the steps to get the output of a subprocess in Python.
Step 1: Import the Subprocess Module
First, we need to import the subprocess
module. You can do this by adding the following line of code to your Python script:
1 |
import subprocess |
Step 2: Execute External Command
Next, we will execute an external command using the subprocess.run()
function. This function takes a command as an argument, which is a list containing the command and its arguments.
For example, let’s execute the “echo” command:
1 2 |
command = ["echo", "Hello, World!"] result = subprocess.run(command, capture_output=True, text=True, shell=True) |
Here, we used the capture_output=True
argument to capture the output, and the text=True
argument to get the output as a string.
Step 3: Access Output and Error
Now that we have executed the command and captured the output, we can access the output and error using the stdout
and stderr
attributes of the returned object.
Let’s print the output and error of the executed command:
1 2 |
print("Output:", result.stdout) print("Error:", result.stderr) |
If the command execution is successful, you will see the output, and the error will be empty. If there is an error, the error message will be displayed instead.
Step 4: Check Return Code
We can also check the return code of the external command using the returncode
attribute of the returned object.
The return code is the exit status of the command. If it is 0, the command executed successfully. Otherwise, there was an error.
Here’s how to check the return code:
1 |
print("Return Code:", result.returncode) |
If your external command was successful, you should see “Return Code: 0”.
Full Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import subprocess # Define the command and its arguments command = ["echo", "Hello, World!"] # Execute the command result = subprocess.run(command, capture_output=True, text=True, shell=True) # Print the output and error print("Output:", result.stdout) print("Error:", result.stderr) # Check the return code print("Return Code:", result.returncode) |
Output
Output: Hello, World! Error: Return Code: 0
Conclusion
With this tutorial, you can now execute external commands and capture their output using Python’s subprocess module. You can also check for errors and return codes to help with debugging and ensure that your commands are executed correctly.