Redirecting stdout, stderror to file while stderr still prints to screen

蹲街弑〆低调 提交于 2019-12-25 18:23:25

问题


I would like stdout and stderr to be redirected to the same file, while stderr still writes to the screen. What's the most pythonic way to do this?


回答1:


I'm assuming you want to redirect the current script's stdout and stderr, not some subprocess you're running.

This doesn't sound like a very Pythonic thing to do in the first place, but if you need to, the Pythonic solution would be:

  • Redirect stdout to a file.
  • Redirect stderr to a custom file-like object that writes to the file and also writes to the real stderr.

Something like this:

class Tee(object):
    def __init__(self, f1, f2):
        self.f1, self.f2 = f1, f2
    def write(self, msg):
        self.f1.write(msg)
        self.f2.write(msg)

outfile = open('outfile', 'w')

sys.stdout = outfile
sys.stderr = Tee(sys.stderr, outfile)



回答2:


Your best bet is to use the python logging framework to send your messages to both places, instead of actually redirecting stdout / stderr. As a less-pythonic alternative, you could make a custom file-like object that's write method will write to both sys.__stdout__ and your file, and assign sys.stdout to your custom object. You would then do the same for stderr. Please see the documentation for the sys module



来源:https://stackoverflow.com/questions/26347191/redirecting-stdout-stderror-to-file-while-stderr-still-prints-to-screen

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