Created
July 12, 2017 09:27
-
-
Save yeondudad/d8e007af49e58ce71b2f60ac77bcc205 to your computer and use it in GitHub Desktop.
how to capture stdout & stderr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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