Skip to content

Instantly share code, notes, and snippets.

@claytantor
Created June 18, 2017 21:59
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 claytantor/b4c7473bd76b3b273a77152c3e0000c9 to your computer and use it in GitHub Desktop.
Save claytantor/b4c7473bd76b3b273a77152c3e0000c9 to your computer and use it in GitHub Desktop.
capturing both stderr and std to a single list of strings.
from cStringIO import StringIO
class Capturing(list):
def __enter__(self):
self._stdout = sys.stdout
self._stderr = sys.stderr
sys.stdout = self._stringio = StringIO()
sys.stderr = self._stringio
return self
def __exit__(self, *args):
self.extend(self._stringio.getvalue().splitlines())
del self._stringio # free up some memory
sys.stdout = self._stdout
sys.stderr = self._stderr
@claytantor
Copy link
Author

# creates a list
with Capturing() as output:
    print "foo" #can also send to stderr

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment