[Tutor] How to redirect console output to a TextEdit box on a QT Python Gui ?

Prasad, Ramit ramit.prasad at jpmorgan.com
Wed Jun 19 22:44:06 CEST 2013


SM wrote:
> Hello Chris, Thanks for your response. I have a follow-up question, if you don't mind, to understand
> your answer better.
> I am running a python3 script. So  first part of your answer applies here:
> 
> "If the application you run is a Python script, import it, execute the
> functions and have the data returned (as opposed to printing it), and
> then you can do self.textEdit.setText(output_
> goes_here)"
> My python script prints a lot of text at various stages. There are "print" statements spread across
> multiple python files.  So when you say "have the data returned" and "output_goes_here" as the
> argument of setText, I am a bit confused as to how I can redirect multiple print statements to the
> setText call. Can you please clarify?
> 
> Thanks!
> Sm

Usually your logic functions should not print (except for debugging). It should return
data which you can then wrap in a UI which prints or displays on GUI. He does not mean to 
actually redirect output but instead do each "stage" and then print/display the appropriate 
text *after* the task is done.

Instead of trying to redirect output you can try logging to file and having the GUI read that file
and print what is appropriate. 

You can also try to replace stdout with an in-memory buffer which you aggregate and then display after 
the stage (or at any point) like this (untested).

self.oldstdout = sys.stdout
sys.stdout = cStringIO.StringIO()
# Do processing stages
# And later
self.textEdit.setText( sys.stdout.getvalue() )
# Replace stdout if needed
sys.stdout = self.oldstdout


~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Tutor mailing list