3

I worked with a bunch of examples I Googled, and looked at a bunch of questions about threading here on stackoverflow, but I still can't seem to get it.

Here is some sample code I am working with:

class Debugger(QTextBrowser):
    def __init__(self, parent):
        super(Debugger, self).__init__(parent)
        sys.stdout = self

    def write(self, text):
        self.moveCursor(QTextCursor.End)
        self.textCursor().insertText(text)

Basically, I am trying to catch any 'print' statements or other forms of writing to the stdoutstream. But I can't get it to print them one by one as they arrive. Instead, it waits until whatever process that prints the strings is finished, and then begins to log the information. So how do I thread this properly?

Edit: Reduced code to bare minimum.

Jeff
  • 968
  • 1
  • 10
  • 25
  • I'm not sure, but I suspect that what is happening here is that the `write`s to `STDOUT` or whatever are note written out until the stream has been `flush()`'d. In which case, if your own code is doing the writing, make sure you call `flush()` on the stream as soon as you write to it, if it's client code you just have to wait. – snim2 Jan 19 '12 at 10:38
  • That's not the issue. I tried the following: 1)added `self.oldstdout = sys.stdout` to the `Debugger.__init` 2)added `self.console.oldstdout.write(text)` to the `StdoutStream.write`. And this happened: The python console printed the strings right away, but the Debugger QTextBrowser waited until the entire process had finished. – Jeff Jan 19 '12 at 11:14
  • Possible duplicate of http://stackoverflow.com/questions/2859256/how-to-redirect-a-python-console-output-to-a-qtextbox – synthesizerpatel Jan 20 '12 at 09:04
  • I took a look. The answer over there is specifically related to `QProcess` I don't understand how to port its specific functionality over to my question, as the `print` statements may not (probably won't) originate in a `QProcess` – Jeff Jan 20 '12 at 09:22

1 Answers1

0

I suspect you are running it all in one thread?

While the other code is running the Qt mainloop is not being runned, therefore it is not processing events (drawing on the screen, taking input, etc.). So while the textbox internally is being updated, it is not being painted on the screen, until your task completes, and then the window is redrawn.

The best solution is to run the process that is doing output (and taking some time) in a separate thread.

A quick-n-dirty solution is to manually iterate the Qt mainloop whenever you have written something to the textbox, see IPython iterate main loop manually?.

Community
  • 1
  • 1
mchro
  • 46
  • 4