7

我试图了解如何创建自定义打印功能。(使用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 自己!)

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

4

3 回答 3

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()

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

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

    def write(self, text):
        #text = text.rstrip()
        #if len(text) == 0: return
        self.old_stdout.write('custom Print--->' + text + '\n')
于 2013-02-20T18:00:13.253 回答
4

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

#!/usr/bin/env python
from __future__ import print_function

from contextlib import contextmanager


#############################
@contextmanager
def no_stdout():
    import sys
    old_stdout = sys.stdout

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

        def write(self, text):
            if len(text.rstrip()):
                self.old_stdout.write('custom Print--->' + text)

    sys.stdout = CustomPrint(old_stdout)

    try:
        yield
    finally:
        sys.stdout = old_stdout


#############################
print("BEFORE")
with no_stdout():
    print("WHY HELLO!\n")
    print("DING DONG!\n")

print("AFTER")

以上产生:

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

代码需要整理,尤其是。围绕班级应该做什么 WRT 将标准输出设置回原来的样子。

于 2013-02-20T18:12:54.097 回答
1

怎么办from __future__ import print_function。这样,您将使用 Python3 的打印函数而不是 Python2 的打印语句。然后你可以重新定义打印功能:

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

但是有一个问题,您必须开始使用打印功能。

于 2013-02-20T17:52:45.273 回答