2013-04-07 65 views
8

在我的程序中有很多print函數(python 2.7)。有什麼辦法可以添加幾行然後所有的輸出可以重定向到stderr?我想要的是Python代碼,但不是Linux管道。在python中,我可以將打印函數的輸出重定向到stderr嗎?

例如,我的計劃是這樣的:

print 'hello world' 

我想添加一些代碼,如:

redirect_output_to_stderr() 
print 'hello world' 

然後所有的輸出可以重定向到stderr

我知道print >> sys.stderr, 'hello world'可以實現我的目標,但它是否可以防止修改已存在的代碼?

+1

code_是使用shell的重定向命令。 – 2013-04-07 08:42:07

+0

哦,我想我需要的是防止修改現有的「打印」功能。感謝你提到:) – waitingkuo 2013-04-07 08:45:08

回答

7

在你的方法做到這一點:

import sys 
sys.stdout = sys.stderr 
2

重新定義print是Python功能3+。但是,您可以將sys.stdout更改爲std.stderr

參見:another question

+2

如果你從'__future__ import print_function'執行'',你*可以*在2.7中重新定義'print'。 – lvc 2013-04-07 08:44:14

+0

@lvc不知道。 「stdout」的改變比函數重定義更短。 – kravemir 2013-04-07 08:47:51

16

在Python 2.7版,你可以這樣做:

import sys 

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

也可以導入從3.x中的行爲:_only_辦法做到這一點_without修改

from __future__ import print_function 
import sys 

print('To stderr.', file=sys.stderr) 
相關問題