Python traceback.print_exc()打印到标准错误(stdout)还是标准输出(stderr)?

12

我已阅读一些Python文档,但我无法找到print_exc函数打印的位置。所以我在Stack Overflow上搜索了一些内容,它说“print_exc()将格式化的异常输出到标准输出(stdout)”。链接

我一直很困惑...在我看来,该函数应该将错误信息打印到stderr,因为它是错误!..哪个是正确的?


1
仔细阅读文档:print_excprint_exception(*sys.exc_info(), limit, file, chain) 的简写。print_exception 的文档说:它与 print_tb 相同,除了<某些内容>。而 print_tb 的文档则表示,默认情况下会打印到 sys.stderr - Op De Cirkel
1
然后,我认为第二个链接是错误的。非常感谢你,@OpDeCirkel! - youngminz
2
我在另一篇帖子中添加了一条评论,以减少将来的混淆。 - tdelaney
3个回答

16

它会打印到stderr,可以从以下测试中看到:

$ cat test.py
try:
    raise IOError()
except:
    import traceback
    traceback.print_exc()
$ python test.py
Traceback (most recent call last):
  File "test.py", line 2, in <module>
     raise IOError()
IOError
$ python test.py > /dev/null
Traceback (most recent call last):
  File "test.py", line 2, in <module>
     raise IOError()
IOError
$ python test.py 2> /dev/null
$

7

顺便提一下,你也可以控制它:

import traceback
import sys



try:
    raise Exception
except Exception as E:
    traceback.print_exc(file=sys.stderr)

6
根据Python文档,"如果省略文件或为None,则输出将发送到sys.stderr;否则,它应该是一个打开的文件或类似文件的对象以接收输出。" 这意味着您可以控制输出的打印方式和位置。
with open(outFile) as fp
    print_exc(fp)

以上示例将输出到文件“outFile”。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接