redirect_stdout in Python: Sending print output to a file

redirect_stdout in Python: Sending print output to a file

Writing a bunch to non-stdout in Python? You might want to use redirect_stdout from contextlib:

from contextlib import redirect_stdout
with redirect_stdout(open('output.txt', 'w')):
    # in this block, stdout goes to output.txt
    print('hi 1')