gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:56:45 25 4
gpt4 key购买 nike

我正在尝试了解如何创建自定义打印功能。(使用 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??...'

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

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

>>>

我只想打印一行:

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

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

我怎样才能使这项工作?还是我的方法完全错误...

最佳答案

这不是递归。您的 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()

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

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

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

关于python:将 sys.stdout 打印更改为自定义打印功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14986490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com