How To Get Stdout In Python

In this tutorial, we will learn how to capture the stdout (output from the standard output) generated by a program in Python.

Capturing stdout can be useful while debugging, logging, or testing your programs. We will demonstrate this with a simple example using Python’s built-in io.StringIO and contextlib.redirect_stdout functionalities.

Step 1: Import the necessary libraries

First, let’s import the required Python libraries for capturing the stdout:

Here, we import io for input and output manipulations, sys to access system-specific parameters, and redirect_stdout from contextlib to temporarily redirect the output.

Step 2: Write a function to capture stdout

Next, let’s create a function that captures the standard output of a given Python function. Our function will accept the target function and its arguments as input parameters.

In this function, we create a StringIO buffer that serves as a temporary storage to capture the stdout. Then, we use redirect_stdout to redirect stdout to the StringIO buffer, call the given function and capture the output in captured_output variable.

Step 3: Use the capture_stdout function

Now, let’s test our capture_stdout function with a simple example. We will create a function named print_hello that prints a “Hello, World!” message to stdout. Then, we will use our capture_stdout function to capture the message printed by the print_hello function.

In this example, we call the capture_stdout function with the print_hello function as the target. The output of the print_hello function is captured and printed by the capture_stdout function.

Full Code

Here is the full code for the example explained above:

When you execute this code, you will see the following output:


Captured Output:
Hello, World!

As expected, the stdout generated by the print_hello function is captured and printed by the capture_stdout function.


In this tutorial, we have learned how to capture stdout in Python using a custom function with the help of io.StringIO and contextlib.redirect_stdout libraries. This functionality can be very useful for debugging, logging, or testing your Python code.

We also demonstrated this approach with a simple example, that can be expanded for more complex scenarios.