python获取函数执行过程中产生的标准输出

import traceback
from io import StringIO
import sys


class Capturing(list):
    def __enter__(self):
        self._stdout = sys.stdout
        # 将err、out输出到内存中
        sys.stderr = sys.stdout = self._stringio = StringIO()
        return self

    def __exit__(self, *args):
        self.extend(self._stringio.getvalue().splitlines())
        # 释放内存
        del self._stringio
        sys.stdout = self._stdout


def test():
    print('asdfadfafafsdf')


with Capturing() as output:
    print('hello world')
    try:
        1 / 0
    except Exception as e:
        traceback.print_exc()

test()
print('output:', output)

参考链接:https://www.it1352.com/1990598.html

上一篇:转换流:指定编码 读取文本文件和写出文本文件


下一篇:JAVASSM整合配置