← 中文资源

简体中文版本

redirect_stdout 捕获 print 输出

测试里捕获 print 输出:redirect_stdout 把 sys.stdout 换成 StringIO,with 块结束自动还原,捕获内容用 getvalue 取回。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

captured lines: 4
REPORT
  parse     91
  write     78
END

restored: outside the with block again

实现说明

redirect_stdout 捕获 print 输出的核心是函数 render_report。 for name, score in rows 承担全部的逐项处理。

使用要点

  • 跑完文件,输出里会留下标记——REPORT、END、captured lines:。
  • render_report 是公开入口,文件里其余部分都是为它服务的内部实现。

常见问题

这段代码会引入外部包吗?

不涉及外部包,每个调用都落在内建 API 上。 文件在加载时定义 render_report。

主签名形如 def render_report(rows)

核心语句

with redirect_stdout(buffer):
    render_report([('parse', 91), ('write', 78)])
def render_report(rows):
    print('REPORT')
    for name, score in rows:
        print(f'  {name:<8} {score:>3}')
    print('END')

代码示例

from contextlib import redirect_stdout
from io import StringIO


def render_report(rows):
    print('REPORT')
    for name, score in rows:
        print(f'  {name:<8} {score:>3}')
    print('END')


# print 写的是 sys.stdout:测试时把它换成 StringIO 即可捕获
buffer = StringIO()
with redirect_stdout(buffer):
    render_report([('parse', 91), ('write', 78)])

captured = buffer.getvalue()
print('captured lines:', len(captured.splitlines()))
print(captured)

# with 块结束后 stdout 自动还原,后续 print 回到控制台
print('restored: outside the with block again')