title: PyQt: displaying Python interpreter output
body: <p>I've implemented <a href="https://stackoverflow.com/a/8356465/889604">this answer</a> into my code, which I was hoping would do what I want. However, I'm running a method via a connection on a <code>QPushButton</code>, and I want to pipe what happens in this method to the GUI.</p>
  
  <p>The first time I click the button the <code>stdout</code> appears in the interpreter window; however, on subsequent presses of the button, the <code>stdout</code> appears in the <code>QTextEdit</code> - I assume there's some intricacy of the print statement, or of <code>QPushButton</code>, that I don't understand - if anyone can give any pointers where I need to start changing my code I'll be eternally grateful!</p>
  
  <p>I think this is the smallest amount of code I can use to demonstrate the problem..</p>
  
  <pre><code>import os, sys
  from PyQt4 import QtCore, QtGui 
  
  def main(): 
    app = QtGui.QApplication(sys.argv) 
    w = MyWindow() 
    w.show() 
    sys.exit(app.exec_()) 
  
  class MyWindow(QtGui.QWidget): 
    def __init__(self, *args): 
      QtGui.QWidget.__init__(self, *args) 
      self.runBtn = QtGui.QPushButton('Run!', self)
      self.runBtn.clicked.connect(self.runCmd)
      self.te = QtGui.QTextEdit()
  
      layout = QtGui.QVBoxLayout(self)
      layout.addWidget(self.runBtn)
      layout.addWidget(self.te)
      self.setLayout(layout) 
  
    def runCmd(self):
      print "here"
      print sys.stdout
      sys.stdout = EmittingStream(textWritten=self.normalOutputWritten)
  
    def __del__(self):
      sys.stdout = sys.__stdout__
  
    def normalOutputWritten(self, text):
      cursor = self.te.textCursor()
      cursor.movePosition(QtGui.QTextCursor.End)
      cursor.insertText(text)
      self.te.setTextCursor(cursor)
      self.te.ensureCursorVisible()
  
  class EmittingStream(QtCore.QObject):
    textWritten = QtCore.pyqtSignal(str)
    def write(self, text):
      self.textWritten.emit(str(text))
  
  if __name__ == "__main__": 
    main()
  </code></pre>