redirect_stdout Captures Print Output
Capture print output in tests by redirecting sys.stdout into a StringIO inside redirect_stdout; the with block restores the real stdout automatically.
Code
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')Output
Captured from a sandboxed run of this snippet in the build pipeline.
captured lines: 4
REPORT
parse 91
write 78
END
restored: outside the with block againHow it works
redirect_stdout Captures Print Output keeps everything in the function render_report.
The file repeats itself only inside for name, score in rows.
Applying it
The main signature reads def render_report(rows)
The demo output is labeled (REPORT, END, captured lines:), so every printed line maps back to its originating operation.
Treat render_report as the API: import it, and ignore the supporting code.
Statements that matter
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')
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.
FAQ
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. The file defines `render_report` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.