将 stdout、stderror 重定向到文件,而 stderr 仍然打印到屏幕 [英] Redirecting stdout, stderror to file while stderr still prints to screen

查看:52
本文介绍了将 stdout、stderror 重定向到文件,而 stderr 仍然打印到屏幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望 stdout 和 stderr 被重定向到同一个文件,而 stderr 仍然写入屏幕.执行此操作的最 Pythonic 方法是什么?

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?

推荐答案

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

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

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

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:

  • stdout 重定向到一个文件.
  • stderr 重定向到一个自定义的类文件对象,该对象写入文件并写入真正的 stderr.
  • 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.

像这样:

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)

这篇关于将 stdout、stderror 重定向到文件,而 stderr 仍然打印到屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆