Intercept python's `print` statement and display in GUI
Question: I have this somewhat complicated command line function in Python (lets call it
`myFunction()`), and I am working to integrate it in a graphical interface
(using PySide/Qt).

The GUI is used to help select inputs, and display outputs. However,
`myFunction` is designed to work as a stand-alone command line function, and
it occasionnaly prints out the progress.

My question is: how can I intercept these `print` calls and display them in
the GUI? I know it would be possible to modify `myFunction()` to send
`processEvents()` to the GUI, but I would then lose the ability to execute
`myFunction()` in a terminal.

Ideally, I would like something similar to Ubuntu's graphical software
updater, which has a small embeded terminal-looking widget displaying what
`apt-get` would display were it executed in a terminal.


Answer: you could redirect stdout and restore after. for example:

    
    
    import StringIO
    import sys
    
    # somewhere to store output
    out = StringIO.StringIO()
    
    # set stdout to our StringIO instance
    sys.stdout = out
    
    # print something (nothing will print)
    print 'herp derp'
    
    # restore stdout so we can really print (__stdout__ stores the original stdout)
    sys.stdout = sys.__stdout__
    
    # print the stored value from previous print
    print out.getvalue()
    

