Nico Schlömer Nico Schlömer - 1 year ago 143
Python Question

How to capture stdout output from a Python function call?

I'm using a Python library that does something to an object


and changes it. While doing so, it prints some statistics to stdout, and I'd like to get a grip on this information. The proper solution would be to change
to return the relevant information,

out = do_something(my_object)

but it will be a while before the devs of
get to this issue. As a workaround, I thought about parsing whatever
writes to stdout.

How can I capture stdout output between two points in the code, e.g.,

out = end_capturing()


Answer Source

Try this context manager:

from cStringIO import StringIO
import sys

class Capturing(list):
    def __enter__(self):
        self._stdout = sys.stdout
        sys.stdout = self._stringio = StringIO()
        return self
    def __exit__(self, *args):
        del self._stringio    # free up some memory
        sys.stdout = self._stdout


with Capturing() as output:

output is now a list containing the lines printed by the function call.

Advanced usage:

What may not be obvious is that this can be done more than once and the results concatenated:

with Capturing() as output:
    print 'hello world'

print 'displays on screen'

with Capturing(output) as output:  # note the constructor argument
    print 'hello world2'

print 'done'
print 'output:', output


displays on screen                     
output: ['hello world', 'hello world2']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download