python:将sys.stdout打印更改为自定义打印功能

and*_*soa 5 python stdout operator-overloading

我试图了解如何创建自定义打印功能.(使用python 2.7)

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??...'
Run Code Online (Sandbox Code Playgroud)

上面的代码将此打印到控制台:

>>> 
custom Print--->why you make 2 lines??...
custom Print--->

>>> 
Run Code Online (Sandbox Code Playgroud)

我想只打印一行:

>>>    
1custom Print--->why you make 2 lines??...
>>>
Run Code Online (Sandbox Code Playgroud)

但是无法弄清楚如何使这个自定义打印工作,我明白有某种递归触发第二个输出到控制台(我使用self.write,将stdout分配给self.write自己!)

我怎么能做这个工作?或者我的做法完全错了......

pio*_*kuc 5

这不是递归。发生的情况是您的write函数被调用两次,一次是您期望的文本,第二次是'\n'. 尝试这个:

import sys
class CustomPrint():
    def __init__(self):
        self.old_stdout=sys.stdout

    def write(self, text):
        text = text.rstrip()
        if len(text) == 0: return
        self.old_stdout.write('custom Print--->' + text + '\n')

    def flush(self):
        self.old_stdout.flush()
Run Code Online (Sandbox Code Playgroud)

我在上面的代码中所做的是将换行符添加到第一次调用中传递的文本中,并确保由 print 语句进行的第二次调用,即用于打印新行的调用,不打印任何内容。

现在尝试注释掉前两行,看看会发生什么:

    def write(self, text):
        #text = text.rstrip()
        #if len(text) == 0: return
        self.old_stdout.write('custom Print--->' + text + '\n')
Run Code Online (Sandbox Code Playgroud)