我的程序中有很多print
函数(python 2.7
)。有什么方法可以添加几行,然后所有输出都可以重定向到 stderr
?我想要的是 python 代码,而不是 linux 管道。
比如我的程序是这样的:
print 'hello world'
我想添加一些代码,例如:
redirect_output_to_stderr()
print 'hello world'
然后所有输出都可以重定向到stderr
。
我知道print >> sys.stderr, 'hello world'
可以达到我的目的,但有什么方法可以防止修改现有代码吗?
最佳答案
在 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)
关于python - 在 python 中,我可以将 print 函数的输出重定向到 stderr 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15860372/