How to Get Output from a Print Statement of a Black Box Function in Python

Viewed 29

Let's say you have a function that you aren't allowed to modify, but you are able to call it. When you call it, how do you retrieve the output from the print statements such that you can store it in a variable?

2 Answers

The python print function is just a write operation to sys.stdout so you can implement a custom stdout class that switches sys.stdout with itself and implements a write method that will save the write() argument to a variable before calling the original method.

edit: https://code.activestate.com/recipes/119404-print-hook/ - this seems to do it

Here is one way to do it

import io
from contextlib import redirect_stdout

out = io.StringIO()
with redirect_stdout(out):
    print("bla")

out.getvalue() # returns 'bla\n'
Related