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

那年仲夏 提交于 2019-11-29 06:04:55

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!