wai*_*kuo 9 python stderr python-2.7
我的程序中有很多print函数(python 2.7).有什么方法可以添加几行然后所有输出都可以重定向到stderr?我想要的是python代码,但不是linux管道.
例如,我的程序如下:
print 'hello world'
Run Code Online (Sandbox Code Playgroud)
我想添加一些代码,如:
redirect_output_to_stderr()
print 'hello world'
Run Code Online (Sandbox Code Playgroud)
然后可以将所有输出重定向到stderr.
我知道print >> sys.stderr, 'hello world'可以实现我的目标,但是它能否阻止修改现有代码?
Rol*_*ith 19
在python 2.7中,您可以:
import sys
print >> sys.stderr, "To stderr."
Run Code Online (Sandbox Code Playgroud)
或者您可以从3.x导入行为:
from __future__ import print_function
import sys
print('To stderr.', file=sys.stderr)
Run Code Online (Sandbox Code Playgroud)
在您的方法中执行此操作:
import sys
sys.stdout = sys.stderr
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13269 次 |
| 最近记录: |