Python - reset stdout to normal, after previously redirecting it to a file

open file and exchange sys variable with file variable

f = open("sample.txt", "w")

sys.stdout, f = f, sys.stdout
print("sample", flush=True)

and take it back

f, sys.stdout = sys.stdout, f
print("sample")

The same holds for stderr, of course. At the end, these lines are needed to get the original streams.

sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__

Another common practice is to store the default stdout and / or stdin and then return them once you are finished with sending your output / input to custom streams. For instance:

orig_stdout = sys.stdout
sys.stdout = open('stdout_file', 'w')
sys.stdout = orig_stdout

The original stdout can be accessed as sys.__stdout__. This is documented.

Tags:

Python

Stdout