Categories
Python Answers

How to capture stdout output from a Python function call?

Spread the love

Sometimes, we want to capture stdout output from a Python function call.

In this article, we’ll look at how to capture stdout output from a Python function call.

How to capture stdout output from a Python function call?

To capture stdout output from a Python function call, we can use the redirect_stdout function.

For instance, we write

import io
from contextlib import redirect_stdout

f = io.StringIO()
with redirect_stdout(f):
    do_something(my_object)
out = f.getvalue()

to call redirect_stdout with the f StringIO object.

Then we call do_something which prints stuff to stdout.

And then we get the value printed to stdout with f.getvalue.

Conclusion

To capture stdout output from a Python function call, we can use the redirect_stdout function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *