zoukankan      html  css  js  c++  java
  • python 源码常见的日志用法io.StringIO()和sys.stdout

    经常看到源码里面有相关的日志操作特地整理一下

    1. 基础知识
    from io import StringIO
    
    #StringIO模块主要用于在内存缓冲区中读写数据
    s = StringIO()
    s.write("www.baidu.com
    ")
    s.write("www.google.com")
    print(s.getvalue())
    '''
    www.baidu.com
    www.google.com
    '''
    
    1. 具体用法
    '''
    test1.py
    '''
    # redirect sys.stdout to a buffer
    import sys, io
    stdout = sys.stdout   #用于恢复sys.stdout
    sys.stdout = io.StringIO()
    
    # call module that calls print()
    import test2 
    test2.test()   #调用test2的print
    
    # get output and restore sys.stdout
    output = sys.stdout.getvalue()
    sys.stdout = stdout  #恢复sys.stdout
    
    print(output)
    '''
    in  test2
    '''
    
    '''
    test2.py
    '''
    def test():
        print('in ',__name__)
    
    1. 源码中的使用
    
    class OutputRedirector(object):
        """ Wrapper to redirect stdout or stderr """
        def __init__(self, fp):
            self.fp = fp
    
        def write(self, s):
            self.fp.write(s)
    
        def writelines(self, lines):
            self.fp.writelines(lines)
    
        def flush(self):
            self.fp.flush()
    
    stdout_redirector = OutputRedirector(sys.stdout)
    stderr_redirector = OutputRedirector(sys.stderr)
    
    ...
    TestResult = unittest.TestResult
    
    class _TestResult(TestResult):
    ...
    
        def startTest(self, test):
            TestResult.startTest(self, test)
            # just one buffer for both stdout and stderr
            self.outputBuffer = io.StringIO()
            stdout_redirector.fp = self.outputBuffer
            stderr_redirector.fp = self.outputBuffer
            self.stdout0 = sys.stdout
            self.stderr0 = sys.stderr
            sys.stdout = stdout_redirector
            sys.stderr = stderr_redirector
    
    
    
  • 相关阅读:
    redis总结
    java程序启动脚本
    mysql生成百万测试数据脚本
    java分布式锁的实现及在springboot中的应用
    mysql使用总结
    一个java实现代码(服务)编排的思路(未完)
    sentinel自定义统一限流降级处理
    shell学习
    oracle查看被锁的事务进程sql
    Sql查询两个时间段有重叠的记录
  • 原文地址:https://www.cnblogs.com/amize/p/13268499.html
Copyright © 2011-2022 走看看