contextlib.redirect_stdout in Python

Level 4210 keystrokes

This redirects stdout to a StringIO buffer to capture print output.

Python code

# redirect_stdout temporarily sends print output elsewhere
1from contextlib import redirect_stdout
# StringIO is a text stream kept in memory
2from io import StringIO
3
# Create an empty buffer to collect the output
4buffer = StringIO()
# Inside this block, print writes to buffer instead of the screen
5with redirect_stdout(buffer):
# Nothing is shown; "Hello\n" goes into the buffer
6 print("Hello")
7 print("World")
8
# Read everything written so far: 'Hello\nWorld\n'
9captured = buffer.getvalue()
# stdout is restored; repr() shows the newlines as \n
10print(f"Captured: {repr(captured)}")

Output

Captured: 'Hello\nWorld\n'
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • (× 7
  • )× 7
  • "× 6
  • _× 2
  • :× 2
  • =× 2
  • .× 1
  • {× 1
  • }× 1

More Python examples at level 4

← Python typing practice