How To Get Output Of Subprocess Python

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:

Step 2: Execute External Command

Next, we will execute an external command using the 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:

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:

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:

If your external command was successful, you should see “Return Code: 0”.

Full Example


Output: Hello, World!
Return Code: 0


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.