fork download
  1. import sys
  2. from io import StringIO
  3. from contextlib import contextmanager
  4.  
  5. @contextmanager
  6. def print_interceptor(buf):
  7. real_stdout = sys.stdout
  8. sys.stdout = buf
  9. yield
  10. sys.stdout = real_stdout
  11.  
  12. buf = StringIO()
  13. with print_interceptor(buf):
  14. print("Hello, world!")
  15.  
  16. print("Intercepted: " + repr(buf.getvalue()))
Success #stdin #stdout 0.01s 10376KB
stdin
Standard input is empty
stdout
Intercepted: 'Hello, world!\n'