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

Question:

At the beginning of my python program I have the following line:

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

Halfway through my program I would like to set stdout back to the normal stdout. How do I do this?

Asked By: tadasajon

||

Answers:

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

Answered By: BrenBarn

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__
Answered By: Philipp

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
Answered By: trozzel

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")
Answered By: armancj2
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.