当stderr仍然打印到屏幕时,将stdout,stderr重定向到文件

时间:2014-10-13 19:10:31

标签: python redirect stderr

我希望将stdout和stderr重定向到同一个文件,而stderr仍然会写入屏幕。什么是最蟒蛇的方式呢?

2 个答案:

答案 0 :(得分:1)

我假设你想重定向当前脚本的stdout和stderr,而不是你正在运行的某个子进程。

这听起来不像是一个非常Pythonic的事情,但如果你需要,Pythonic解决方案将是:

  • stdout重定向到文件。
  • stderr重定向到写入文件的自定义文件对象,并写入真实stderr

这样的事情:

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)

答案 1 :(得分:0)

最好的办法是use the python logging framework将邮件发送到这两个地方,而不是实际重定向stdout / stderr。作为一个不那么pythonic的替代,you could make a custom file-like object that's write method will write to both sys.__stdout__ and your file,并将sys.stdout分配给您的自定义对象。然后你会为stderr做同样的事情。请参阅documentation for the sys module