簡體   English   中英

嘗試重定向標准輸出時出現無限循環

[英]Infinite loop when try to redirect stdout

我正在嘗試將stdout發送到控制台和QTextBrowser小部件。 但是我遇到了某種無限循環,然后應用程序退出。

這是我的代碼:

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_())

結果,當單擊start_button時,觀察到以下內容:

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

Process finished with exit code 1

我只是不明白為什么這條線會造成循環:

self.log_browser.setText(message)

第一個答案后編輯:

我將上面的行替換為print(message) ,但仍然得到相同的結果。 我將不勝感激任何幫助。

看起來您發布的代碼不是您運行的代碼,但是假設它具有代表性,則有兩個錯誤:必須初始化Logger的基類,並且self.log_browser不在任何地方定義。 但這不會導致循環,應用程序退出(因為存在異常但沒有異常掛鈎,請參見)。 由於我不知道log_browser應該是什么,我將其定義為Mock()(來自unittest.mock),它將接受對其進行的所有操作,問題就消失了。

class Logger(QObject):
    def __init__(self):
        super().__init__()
        self.terminal = sys.stdout
        from unittest.mock import Mock
        self.log_browser = Mock()

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

    def flush(self):
        pass

您可以從Logger發出自定義信號,然后將其連接到日志瀏覽器:

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_())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM