I'm trying to save results from printing the help of a function in a file, instead of presenting them on the cell output in Google Colab.
My code is below:
import sys
import io
def capture_help_to_buffer(obj):
output_buffer = io.StringIO()
sys.stdout = output_buffer
try:
help(obj)
except:
pass
sys.stdout = sys.__stdout__
return output_buffer.getvalue()
# Example usage
help_output = capture_help_to_buffer(list)
print(help_output)
My problem is: after running this code, print
starts returns nothing. In other words: it seems that the reassiging of sys.stdout
to its supposedly default value (sys.__stdout__
) is not working.
My question: to what value should I reassign sys.stdout
so print
will return to its normal behavior (presenting its output in Google Colab's cell's output)?
You could solve this with contextlib.redirect_stdout
, like so:
import sys
import io
from contextlib import redirect_stdout
def capture_help_to_buffer(obj):
output_buffer = io.StringIO()
with redirect_stdout(output_buffer):
try:
help(obj)
except:
pass
return output_buffer.getvalue()
This creates a context in which stdout
is redirected then restored when you exit the code block.
Here's the contextlib.redirect_stdout
documentation: https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout