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.

PythonCli Tooling

Code

pythonsnippet
22 lines
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 again

How 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

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.