What would cause the inner contents of a `with` statement to not execute?

43 Views Asked by At

When I run the following code, no error messages are printed, and it seems to fail silently. I expected the string "BLAH" to be printed to the console.

from contextlib import redirect_stdout
import io # the initialism `io` represents `INPUT OUTPUT LIBRARY`

def run_solver():
    print("solver is running")

with io.StringIO() as fake_std_out:
    with redirect_stdout(fake_std_out):
        print("BLAH") # THIS IS NEVER PRINTED
        run_solver()
        data = fake_std_out.getvalue()
        print(data)
print("THE END")

The output I expect is:

BLAH
solver is running
THE END

Instead, we have:

THE END

Edits

  1. I realize now that I wanted to copy standard output, not re-direct it.
  2. Using print to print the contents of the string stream won't work because the destination of the print function is now the string stream instead of the system console. After calling getvalue() it makes no sense to attempt to use print statements anymore.
1

There are 1 best solutions below

0
chepner On

The code is working fine. print writes to standard output, not the console directly. You can check for the values written to fake_std_out yourself following the inner with statement.

from contextlib import redirect_stdout
import io

def run_solver():
    print("solver is running")

with io.StringIO() as fake_std_out:
    with redirect_stdout(fake_std_out):
        print("BLAH")
        run_solver()

    assert fake_std_out.getvalue() == 'BLAH\nsolver is running\n'

print("THE END")