python:更改sys.stdout打印到自定义打印功能
我试图了解如何创建自定义打印功能。 (使用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自己!)
我该如何做这项工作?或者是我的做法完全错误...
这不是递归。会发生什么情况是您的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')
我在上面的代码做的是我的新行字符添加到在第一次调用传递文本,并确保通过print语句做出的第二个电话,一个旨在打印新行,不打印任何东西。
现在试评出来的前两行,并看看会发生什么:
def write(self, text):
#text = text.rstrip()
#if len(text) == 0: return
self.old_stdout.write('custom Print--->' + text + '\n')
谢谢,它的工作方式应该是:)不知道\ n是在第二遍时添加的! sys.stderr.write(“:”。join(“{0:b}”.format(ord(c))for c in text))甚至添加了这一行只是为了确保你的权利^^ – andsoa 2013-02-20 18:22:16
有一个小使用逗号分隔的打印时出现问题:'print var1,var2'显然,逗号为每个'var'调用打印并抑制在前面的'var'上添加'\ n'!这可以通过在customPrint类中添加tmp var来解决,该类存储文本,并且仅当文本以'\ n'结尾时才打印。 – andsoa 2013-02-21 13:24:26
@andsoa好的,感谢您分享这个优雅的解决方案,感谢分享 – piokuc 2013-02-21 13:39:04
怎么样做from __future__ import print_function
。这样您将使用Python3打印功能,而不是Python2的打印语句。然后你可以重新定义打印功能:
def print(*args, **kwargs):
__builtins__.print("Custom--->", *args, **kwargs)
有一个问题,你必须开始使用打印功能。
这将工作,但我的情况我需要改变一些类的打印输出写python 2.7 print:/ – andsoa 2013-02-20 18:04:13
一个解决办法可能是使用上下文管理器,如果是本地化。
#!/usr/bin/env python
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将stdout设置回原来的样子。
! – andsoa 2013-02-21 13:14:58
相关:[将stdout重定向到Python中的文件?](http://*.com/q/4675728/4279) – jfs 2015-01-27 11:27:57