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

Im trying to understand how to create a custom print function.

(using 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??...'

The code above prints this to console:

>>>

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

custom Print--->

>>>

and i want to print only one line:

>>>

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

>>>

But cant figure out how to make this custom print work , i understand that there's some kind of recursion that triggers the second output to the console (i use self.write , to assign stdout to self.write himself !)

how can i make this work ? or is my approach just completely wrong...

解决方案

It's not recursion. What happens is your write function is called twice, once with the text you expect, second time with just '\n'. Try this:

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

What I do in the above code is I add the new line character to the text passed in the first call, and make sure the second call made by the print statement, the one meant to print new line, doesn't print anything.

Now try to comment out the first two lines and see what happens:

def write(self, text):

#text = text.rstrip()

#if len(text) == 0: return

self.old_stdout.write('custom Print--->' + text + '\n')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值