python输出重定向,原理与各类方法总结

背景:

1.当我们在python中调用print obj时,事实上是调用了sys.stdout.write(obj + ‘\n’)
print 将你需要的内容打印到了控制台,然后加了一个换行符。
2.当我们用 raw_input('Input promption: ') 时,事实上是先把提示信息输出,然后捕获输入
以下两组在事实上等价:

print 'hello? ', #comma to stay in the same line
hi=sys.stdin.readline()[:-1] # -1 to discard the '\n' in input stream

3.根据背景介绍,我们可以构造一个具有write方法的对象,让他将标准输出重定向,存储到别的位置,如下:

import sys

class __redirection__:
    
    def __init__(self):
        self.buff=''
        self.__console__=sys.stdout
        
    def write(self, output_stream):
        self.buff+=output_stream
        
    def to_console(self):
        sys.stdout=self.__console__
        print self.buff
    
    def to_file(self, file_path):
        f=open(file_path,'w')
        sys.stdout=f
        print self.buff
        f.close()
    
    def flush(self):
        self.buff=''
        
    def reset(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()

文章大部分内容转自:https://www.cnblogs.com/ajianbeyourself/p/6927925.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值