The following Python code provides a context manager that captures the standard output and standard error of the commands in a tuple of stdout, stderr
:
import contextlib
@contextlib.contextmanager
def capture():
import sys
from cStringIO import StringIO
oldout, olderr = sys.stdout, sys.stderr
try:
out = [StringIO(), StringIO()]
sys.stdout, sys.stderr = out
yield out
finally:
sys.stdout, sys.stderr = oldout, olderr
out[0] = out[0].getvalue()
out[1] = out[1].getvalue()
with capture() as out:
One then can use this output for testing of command line scripts generated by entry_point
in the setup.py
or for debugging/sanitising wrapper for command line utilities like PyEPICS.