How to capture stdout output from a Python function call?

Estimated read time 1 min read

To capture the stdout output from a Python function call, you can redirect the standard output to a variable using the io module. Here’s an example:

import sys
from io import StringIO

def my_function():
    print("Hello, world!")

# Create a StringIO object to capture the stdout output
stdout_capture = StringIO()

# Redirect the stdout to the StringIO object
sys.stdout = stdout_capture

# Call the function that prints to stdout
my_function()

# Get the stdout output from the StringIO object
stdout_output = stdout_capture.getvalue()

# Restore the stdout
sys.stdout = sys.__stdout__

# Print the captured stdout output
print("Captured output:", stdout_output)

In this example, the my_function() function prints “Hello, world!” to the standard output (stdout). To capture this output, a StringIO object is created and assigned to stdout_capture. Then, the sys.stdout is redirected to the stdout_capture object using sys.stdout = stdout_capture.

After calling the function, you can retrieve the captured stdout output by calling stdout_capture.getvalue(). Finally, the sys.stdout is restored to its original value (sys.__stdout__) to resume printing to the console.

The captured stdout output can be used or processed further as needed.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply