在跑python脚本时,你想捕获某段代码的输出并塞进字符串里,可以进行如下骚操作

def myfunc():
    print("hahaha")
    raise ValueError('123')

import io
import sys
import traceback

stdout = sys.stdout
sys.stdout = io.StringIO()

try:
    myfunc() # call methods
    # or do something here
except Exception as e:
    print(traceback.format_exc())

sys.stdout = stdout
output = sys.stdout.getvalue()

这样你就可以把正常输出(print)和异常堆栈都放到output了,主要原理是把sys.stdout用一个StringIO对象临时替换掉,用来接收输出,收集完后再把sys.stdout替换成原来的。另外要注意,logging默认的输出不是sys.stdout,因此在中间使用logging模块产生的输出不会被捕获。