Context manager for temporarily redirecting sys.stdout to another file or file-like object.
contextlib.redirect_stdout(new_target)
with redirect_stdout(io.StringIO()) as f:
help(pow)
s = f.getvalue()
with open('help.txt', 'w') as f:
with redirect_stdout(f):
help(pow)
with redirect_stdout(sys.stderr):
help(pow)