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