Python: Revert sys.stdout to default

You can revert to the original stream by reassigning to sys.__stdout__.

From the docs

contain[s] the original values of stdin, stderr and stdout at the start of the program. They are used during finalization, and could be useful to print to the actual standard stream no matter if the sys.std* object has been redirected.

The redirect_stdout context manager may be used instead of manually reassigning:

import contextlib

with contextlib.redirect_stdout(myoutputfile):
    print(output) 

(there is a similar redirect_stderr)

Changing sys.stdout has a global effect. This may be undesirable in multi-threaded environments, for example. It might also be considered as over-engineering in simple scripts. A localised, alternative approach would be to pass the output stream to print via its file keyword argument:

print(output, file=myoutputfile) 

In Python3 use redirect_stdout; a similar case is given as an example:

To send the output of help() to a file on disk, redirect the output to a regular file:

with open('help.txt', 'w') as f:
    with redirect_stdout(f):
        help(pow)