Infinite loop when try to redirect stdout
<p>I'm trying to send stdout to both console and <code>QTextBrowser</code> widget. But I'm getting some kind of infinite loop and then application exits.</p>

<p>Here is my code:</p>

<pre><code>import sys
from PyQt5 import QtWidgets, uic
from PyQt5.QtCore import *

qtCreatorFile = "qt_ui.ui"
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)

class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)
        self.start_button.clicked.connect(printing)

def printing():
    print("Pressed!\n")

class Logger(QObject):
    def __init__(self):
        super().__init__()
        self.terminal = sys.stdout

    def write(self, message):
        self.terminal.write(message)
        self.log_browser.setText(message) #problem is in this line

    def flush(self):
        pass

if __name__ == "__main__":
    sys.stdout = Logger()
    app = QtWidgets.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
</code></pre>

<p>As a result, when click start_button, following is observed:</p>

<pre><code>"C:\...\python.exe" "E:/.../qt_gui.py"
Pressed!
Pressed!
Pressed!
... (totaly 332 times)
Pressed!
Pressed!
Pressed!

Process finished with exit code 1
</code></pre>

<p>I just can't understand why this line makes loop:</p>

<pre><code>self.log_browser.setText(message)
</code></pre>

<p><strong>Edit after 1st answer:</strong></p>

<p>I replaced the line above with <code>print(message)</code>, but still getting same results. I would appreciate any help.</p>

<p>You could emit a custom signal from <code>Logger</code> and connect it to the log browser:</p>

<pre><code>class Logger(QObject):
    loggerMessage = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.terminal = sys.stdout

    def write(self, message):
        self.terminal.write(message)
        self.loggerMessage.emit(message)

    def flush(self):
        pass

if __name__ == "__main__":

    sys.stdout = Logger()
    app = QtWidgets.QApplication(sys.argv)
    window = MainWindow()
    sys.stdout.loggerMessage.connect(window.log_browser.insertPlainText)
    window.show()
    sys.exit(app.exec_())
</code></pre>

python qt python-3.x pyqt