python: getting output from `print` inside a function
Question: Im using a library of functions that some of them print data I need:

    
    
    def func():
       print "data"
    

How can I call this function and get the printed data into a string?


Answer: If you can't change those functions, you will need to redirect `sys.stdout`:

    
    
    >>> import sys
    >>> stdout = sys.stdout
    >>> import StringIO
    >>> s = StringIO.StringIO()
    >>> sys.stdout = s
    >>> print "hello"
    >>> sys.stdout = stdout
    >>> s.seek(0)
    >>> s.read()
    'hello\n'
    

