问题
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?
回答1:
The original stdout can be accessed as sys.__stdout__. This is documented.
回答2:
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__
回答3:
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
来源:https://stackoverflow.com/questions/14245227/python-reset-stdout-to-normal-after-previously-redirecting-it-to-a-file