Skip to content

Instantly share code, notes, and snippets.

@mitsuhiko
Created April 27, 2014 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitsuhiko/11346749 to your computer and use it in GitHub Desktop.
Save mitsuhiko/11346749 to your computer and use it in GitHub Desktop.
$ python3 wtf.py
foo
bar
b''
import io
import sys
import contextlib
class _NonClosingTextIOWrapper(io.TextIOWrapper):
def __del__(self):
pass
@contextlib.contextmanager
def capture_stdout(and_stderr=False):
ll_stream = io.BytesIO()
stream = _NonClosingTextIOWrapper(ll_stream, sys.stdout.encoding,
sys.stdout.errors)
old_stdout = sys.stdout
sys.stdout = stream
if and_stderr:
old_stderr = sys.stderr
sys.stderr = stream
try:
yield ll_stream
finally:
stream.flush()
sys.stdout = old_stdout
sys.stdout.buffer.write(ll_stream.getvalue())
if and_stderr:
sys.stderr = old_stderr
with capture_stdout() as out:
print('foo')
print('bar')
x = out.getvalue()
print(repr(x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment