实现说明
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')