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
- I realize now that I wanted to copy standard output, not re-direct it.
- Using
printto 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 callinggetvalue()it makes no sense to attempt to use print statements anymore.
The code is working fine.
printwrites to standard output, not the console directly. You can check for the values written tofake_std_outyourself following the innerwithstatement.