我試圖瞭解如何創建自定義打印功能。 (使用Python 2.7)python:更改sys.stdout打印到自定義打印功能
import sys
class CustomPrint():
def __init__(self):
self.old_stdout=sys.stdout #save stdout
def write(self, text):
sys.stdout = self.old_stdout #restore normal stdout and print
print 'custom Print--->' + text
sys.stdout= self # make stdout use CustomPrint on next 'print'
# this is the line that trigers the problem
# how to avoid this??
myPrint = CustomPrint()
sys.stdout = myPrint
print 'why you make 2 lines??...'
上面打印的代碼本安慰:
>>>
custom Print--->why you make 2 lines??...
custom Print--->
>>>
,我想只打印一行:
>>>
1custom Print--->why you make 2 lines??...
>>>
,但無法弄清楚如何使這個自定義打印工作,我明白,有某種遞歸觸發第二個輸出到控制檯(我使用self.write,分配標準輸出self.write自己!)
我該如何做這項工作?或者是我的做法完全錯誤...
相關:[將stdout重定向到Python中的文件?](http://stackoverflow.com/q/4675728/4279) – jfs 2015-01-27 11:27:57