Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept python's `print` statement and display in GUI

Tags:

python

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.

like image 586
PhilMacKay Avatar asked Dec 15 '22 09:12

PhilMacKay


1 Answers

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()
like image 164
Corey Goldberg Avatar answered Feb 03 '23 11:02

Corey Goldberg