标签:cto python com flush 读写 unittest ini class module
from io import StringIO
#StringIO模块主要用于在内存缓冲区中读写数据
s = StringIO()
s.write("www.baidu.com\n")
s.write("www.google.com")
print(s.getvalue())
‘‘‘
www.baidu.com
www.google.com
‘‘‘
‘‘‘
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__)
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
python 源码常见的日志用法io.StringIO()和sys.stdout
标签:cto python com flush 读写 unittest ini class module
原文地址:https://www.cnblogs.com/amize/p/13268499.html