【问题标题】:In python, can I redirect the output of print function to stderr?在python中,我可以将打印函数的输出重定向到stderr吗?
【发布时间】:2013-03-29 10:18:25
【问题描述】:

我的程序中有很多print 函数(python 2.7)。有什么办法可以添加几行然后所有输出都可以重定向到stderr?我想要的是 python 代码,而不是 linux 管道。

比如我的程序是这样的:

print 'hello world'

我想添加一些代码,例如:

redirect_output_to_stderr()
print 'hello world'

然后可以将所有输出重定向到stderr

我知道print >> sys.stderr, 'hello world' 可以达到我的目的,但是有什么方法可以防止修改现有代码吗?

【问题讨论】:

  • 在不修改代码的情况下,唯一的方法是使用 shell 的重定向命令。
  • 哦,我想我需要的是防止修改现有的print 函数。谢谢你提到:)

标签: python python-2.7 stderr


【解决方案1】:

在 python 2.7 中你可以这样做:

import sys

print >> sys.stderr, "To stderr."

或者您可以从 3.x 导入行为:

from __future__ import print_function
import sys

print('To stderr.', file=sys.stderr)

【讨论】:

    【解决方案2】:

    print 的重新定义是 Python 3+ 的特性。但是,您可以将sys.stdout 更改为std.stderr

    见:another question

    【讨论】:

    • 如果你这样做from __future__ import print_function,你可以在 2.7 中重新定义 print
    • @lvc 不知道。还是stdout的变化比函数重定义要短。
    【解决方案3】:

    在你的方法中这样做:

    import sys
    sys.stdout = sys.stderr
    

    【讨论】:

    • 或者不要,天哪,这是个可怕的建议。
    • @ruohola 是的,在任何代码中都不是一件好事,即使是 6 年前!但我想这正是问题所要求的¯_(ツ)_/¯
    猜你喜欢
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    • 2012-12-21
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 2011-07-25
    相关资源
    最近更新 更多