如何在 Python 中重定向 stderr? [英] How to redirect stderr in Python?

查看:78
本文介绍了如何在 Python 中重定向 stderr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想记录 Python 脚本的所有输出.我试过了:

I would like to log all the output of a Python script. I tried:

import sys

log = []

class writer(object):
    def write(self, data):
        log.append(data)

sys.stdout = writer()
sys.stderr = writer()

现在,如果我打印‘东西’",它就会被记录下来.但是,如果我犯了一些语法错误,比如打印‘某事#’,它就不会被记录——它会进入控制台.

Now, if I "print 'something' " it gets logged. But if I make for instance some syntax error, say "print 'something# ", it wont get logged - it will go into the console instead.

如何从 Python 解释器中捕获错误?

How do I capture also the errors from Python interpreter?

我在这里看到了一个可能的解决方案:

I saw a possible solution here:

http://www.velocityreviews.com/forums/showpost.php?p=1868822&postcount=3

但第二个示例登录到/dev/null - 这不是我想要的.我想把它记录到一个列表中,就像我上面的例子或 StringIO 之类的......

but the second example logs into /dev/null - this is not what I want. I would like to log it into a list like my example above or StringIO or such...

另外,最好我不想创建子进程(并在单独的线程中读取它的 stdout 和 stderr).

Also, preferably I don't want to create a subprocess (and read its stdout and stderr in separate thread).

推荐答案

您不能在 Python 代码中执行任何可以在编译相同代码期间捕获错误的操作.怎么可能?如果编译器不能完成代码的编译,它就不会运行代码,所以你的重定向还没有生效.

You can't do anything in Python code that can capture errors during the compilation of that same code. How could it? If the compiler can't finish compiling the code, it won't run the code, so your redirection hasn't even taken effect yet.

这就是您的(不需要的)子进程的用武之地.您可以编写重定向标准输出的 Python 代码,然后调用 Python 解释器来编译其他一些代码.

That's where your (undesired) subprocess comes in. You can write Python code that redirects the stdout, then invokes the Python interpreter to compile some other piece of code.

这篇关于如何在 Python 中重定向 stderr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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