Context managers · 8 / 15 Exercise Medium

Capture the output

Objective

Create a Python program that captures what is printed with print inside a with block, using an io.StringIO object from the io module as destination.

Instructions

  • Read an integer n and then n lines of text (read them all before the with block).
  • Inside a with block with redirect_stdout(buffer) (from the contextlib module), print each line in uppercase.
  • Outside the block, get the captured text with buffer.getvalue() and show Captured lines: k, Characters: k and then each captured line preceded by "> ".
Input
3
hola
mundo
x y
Output
Captured lines: 3
Characters: 15
> HOLA
> MUNDO
> X Y

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise