@contextlib.contextmanager
def fake_io(write_func):
 old_stdout = sys.stdout
 old_stderr = sys.stderr
 fake_stderr = FakeIOStream(write_func)
 fake_stdout = FakeIOStream(write_func)
 sys.stderr = fake_stderr
 sys.stdout = fake_stdout
 try:
  (yield)
 finally:
  if (sys.stdout is fake_stdout):
   sys.stdout = old_stdout
  if (sys.stderr is fake_stderr):
   sys.stderr = old_stderr

@ contextlib . contextmanager def fake_io ( write_func ) : old_stdout = sys . stdout old_stderr = sys . stderr fake_stderr = FakeIOStream ( write_func ) fake_stdout = FakeIOStream ( write_func ) sys . stderr = fake_stderr sys . stdout = fake_stdout try : ( yield ) finally : if ( sys . stdout is fake_stdout ) : sys . stdout = old_stdout if ( sys . stderr is fake_stderr ) : sys . stderr = old_stderr
run code with stdout and stderr replaced by fakeiostreams .