Tips and Tricks - Capture Output

There are different built-in as well as third-party functions, which print their output directly to stdout. Suppose you want to capture the result of calling the built-in help() function and process it further. To achieve that, you can utilise the redirect_stdout() function from the contextlib standard library.

For example, you can use a io.StringIO object as the container for the result in combination with contextlib.redirect_stdout(), which directs it to the io.StringIO object:

import contextlib
import io

output_stream = io.StringIO()
with contextlib.redirect_stdout(output_stream):
    help(pow)

output_stream = output_stream.getvalue()
print("value:", output_stream)

An alternative is to provide a file handle to the contextlib.redirect_stdout() function to direct the output to a file:

import contextlib

with open("help.txt", "w") as f:
    with contextlib.redirect_stdout(f):
        help(pow)

Last but not least, you can also direct it to stderr as follows:

import contextlib
import sys

with contextlib.redirect_stdout(sys.stderr):
    help(pow)

Groups: standard library