python:将sys.stdout print更改为自定义打印函数

python:将sys.stdout print更改为自定义打印函数,python,operator-overloading,stdout,Python,Operator Overloading,Stdout,我试图了解如何创建自定义打印功能。 (使用python 2.7) 上面的代码将此打印到控制台: >>> custom Print--->why you make 2 lines??... custom Print---> >>> 我只想打印一行: >>> 1custom Print--->why you make 2 lines??... >>> 但是我不知道如何使这个自定义打印工作,我知

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

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

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

>>> 
我只想打印一行:

>>>    
1custom Print--->why you make 2 lines??...
>>>
但是我不知道如何使这个自定义打印工作,我知道有某种递归会触发控制台的第二个输出(我使用self.write,将stdout分配给self.write自己!)


我怎样才能做到这一点?还是我的方法完全错了…

从未来导入打印功能如何。这样,您将使用Python3的print函数,而不是Python2中的print语句。然后可以重新定义打印功能:

def print(*args, **kwargs):
    __builtins__.print("Custom--->", *args, **kwargs)

不过有一个问题,您必须开始使用print函数。

这不是递归。发生的情况是,
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()
在上面的代码中,我要做的是将新行字符添加到第一次调用中传递的文本中,并确保由print语句进行的第二次调用(用于打印新行的调用)不打印任何内容

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

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

一种解决方案可能是使用本地化的上下文管理器

#/usr/bin/env python
来自未来导入打印功能
从contextlib导入contextmanager
#############################
@上下文管理器
def no_stdout():
导入系统
old_stdout=sys.stdout
类CustomPrint():
定义初始化(自身,标准输出):
self.old\u stdout=stdout
def写入(自身、文本):
如果len(text.rstrip()):
self.old_stdout.write('自定义打印-->'+文本)
sys.stdout=CustomPrint(旧stdout)
尝试:
产量
最后:
sys.stdout=old\u stdout
#############################
打印(“之前”)
不带_stdout():
打印(“为什么打招呼!\n”)
打印(“叮咚!\n”)
打印(“之后”)
上述结果产生:

BEFORE
custom Print--->WHY HELLO!
custom Print--->DING DONG!
AFTER

代码需要整理,尤其是类应该做的事情。请将stdout设置回原来的状态。

这会起作用,但我的案例中,我需要更改一些用python 2.7编写的类的打印输出打印:/谢谢,它的工作方式应该是:)不知道\n是在第二次运行时添加的!sys.stderr.write(“:”.join(“{0:b}”).format(ord(c))for c in text)甚至添加了这一行,只是为了确保和您的权利^^^在使用逗号分隔的打印时有一个小问题:“print var1,var2”显然逗号为每个“var”调用print,并禁止在前面的“var”上添加“\n”!这可以通过在customPrint类上添加tmp变量来解决,该类存储文本,并且仅在文本以“\n”结尾时打印:
BEFORE
custom Print--->WHY HELLO!
custom Print--->DING DONG!
AFTER