zoukankan      html  css  js  c++  java
  • python重定向原理及实例

    1. 前言

    为了在Python编程中, 利用控制台信息, 我们需要对控制台输出进行接管(重定向)。在Python中,控制台输出的接口是sys.stdout,通过分析print与sys.stdout之间的关系,我们就可以实现控制台输出重定向了。

    2. sys.stdout 与 print

    当我们在 Python 中打印对象调用

    print(obj)
    

    的时候,事实上是调用了

    # 在print(obj)的过程中, 会产生两次调用
    sys.stdout.write(obj)
    sys.stdout.write('
    ')
    

    所以, 我们只要创造一个替代的对象, 实现write方法, 就可以进行控制台输出重定向了.

    3. 实战 之 同时重定向到控制台和文件

    import sys
    
    class __redirection__(object):
        def __init__(self, filepath):
            self.filepath = filepath
            self.buff = ''
            self.__console__ = sys.stdout
            sys.stdout = self
    
        def write(self, output_stream):
            self.buff += output_stream
            self.__console__.write(output_stream)
            f = open(self.filepath,'w')
            f.write(self.buff)
            f.close()
    
        def flush(self):
            self.buff = ''
    
        def __del__(self):
            sys.stdout = self.__console__
    
    if __name__ == '__main__':
        def main():
            r_obj=__redirection__(r'd:/temp/test.txt')
    
            print('hello')
            print('__redirection__')
    
        main()
    
  • 相关阅读:
    html问题记录20180529
    html问题记录20180518
    html问题记录20180515
    Redis持久化--AOF
    Redis持久化--RDB
    Redis事件模型
    两个字符串的编辑距离-动态规划方法
    Reactor事件模型在Redis中的应用
    事件驱动模式--Reactor
    IO多路复用--总结
  • 原文地址:https://www.cnblogs.com/yaoyu126/p/9855532.html
Copyright © 2011-2022 走看看