python的sys.stdout重定向

转载自:https://blog.youkuaiyun.com/MTbaby/article/details/53159053

没有找到原文地址,若有人知道原文地址,请告知我,我会修改上面的地址,侵删

本文环境:Python2.7

使用 printobj 而非 print(obj)

1sys.stdoutprint

当我们在 Python中打印对象调用 printobj 时候,事实上是调用了 sys.stdout.write(obj+'\n')

print将你需要的内容打印到了控制台,然后追加了一个换行符

print会调用 sys.stdout write 方法

以下两行在事实上等价:

sys.stdout.write('hello'+'\n')

print'hello'

2sys.stdinraw_input

当我们用raw_input('Input promption: ')时,事实上是先把提示信息输出,然后捕获输入

以下两组在事实上等价:

hi=raw_input('hello?')

print'hello? ', #comma to stay in the same line

hi=sys.stdin.readline()[:-1] # -1 to discard the '\n' in input stream


从控制台重定向到文件

原始的 sys.stdout指向控制台

如果把文件的对象的引用赋给sys.stdout,那么 print调用的就是文件对象的 write方法

f_handler=open('out.log','w')

sys.stdout=f_handler

print'hello'

#this hello can't be viewed on concole

#this hello is in file out.log

记住,如果你还想在控制台打印一些东西的话,最好先将原始的控制台对象引用保存下来,向文件中打印之后再恢复sys.stdout

__console__=sys.stdout

#redirection start #

...

#redirection end

sys.stdout=__console__



同时重定向到控制台和文件

如果我们希望打印的内容一方面输出到控制台,另一方面输出到文件作为日志保存,那么该怎么办?

将打印的内容保留在内存中,而不是一打印就将buffer 释放刷新,那么放到一个字符串区域中会怎样?


a=''

sys.stdout=a

print'hello'

OK,上述代码是无法正常运行的

Traceback(most recent call last): File

".\hello.py",line xx, in print 'hello'

AttributeError:'str'

objecthas no attribute 'write'


错误很明显,就是上面强调过的,在尝试调用sys.stdout.write() 的时候,发现没有write 方法

另外,这里之所以提示attribute error 而不是找不到函数等等,我猜想是因为python将对象/类的函数指针记录作为对象/类的一个属性来对待,只是保留了函数的入口地址

既然这样,那么我们必须给重定向到的对象实现一个write 方法:


importsys

class Redirection:

def__init__(self):

self.buff=''

self.__console__=sys.stdout



defwrite(self, output_stream):

self.buff+=output_stream



defto_console(self):

sys.stdout=self.__console__

printself.buff



defto_file(self, file_path):

f=open(file_path,'w')

sys.stdout=f

printself.buff

f.close()



defflush(self):

self.buff=''



defreset(self):

sys.stdout=self.__console__



if__name__=="__main__":

#redirection

r_obj=Redirection()

sys.stdout=r_obj



#get output stream

print'hello'

print'there'



#redirect to console

r_obj.to_console()



#redirect to file

r_obj.to_file('out.log')



#flush buffer

r_obj.flush()



#reset

r_obj.reset()

同样的,sys.stderr,sys.stdin 也都可以被重定向到多个地址,举一反三的事情就自己动手实践吧



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值