Skip to content

Instantly share code, notes, and snippets.

@yeondudad
Created July 12, 2017 09:27
Show Gist options
  • Save yeondudad/d8e007af49e58ce71b2f60ac77bcc205 to your computer and use it in GitHub Desktop.
Save yeondudad/d8e007af49e58ce71b2f60ac77bcc205 to your computer and use it in GitHub Desktop.
how to capture stdout & stderr
from __future__ import print_function
import contextlib
import sys
from cStringIO import StringIO
def print_error(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
@contextlib.contextmanager
def capture():
out_ = sys.stdout
err_ = sys.stderr
try:
out = [StringIO(), StringIO()]
sys.stdout, sys.stderr = out
yield out
finally:
sys.stdout = out_
sys.stderr = err_
out[0] = out[0].getvalue()
out[1] = out[1].getvalue()
if __name__ == "__main__":
with capture() as out_err:
print('hello out')
print_error('hello err')
print(out_err) # ['hello out\n', 'hello err\n']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment