首页 > 解决方案 > 如何在pyQt中打印控制台输出

问题描述

我需要在 Pyqt 窗口中显示 adb 日志,我试过这样。当我单击按钮时调用 log_display 函数,它将控制台输出设置为 textBrowser。我尝试使用 subprocess 但没有帮助,窗口只是冻结并且没有响应。这样做的方法是什么?也许我需要为此使用新线程?

def log_display(self):
    result = subprocess.run('adb logcat *:I', stdout=subprocess.PIPE)
    self.textBrowser.setText(subprocess.run('result.stdout'))

标签: pythonpyqtadb

解决方案


您必须使用 QProcess,因为它启动应用程序但不会阻止 GUI,因为它通过信号通知日志:

from PyQt5 import QtCore, QtGui, QtWidgets


class LogView(QtWidgets.QPlainTextEdit):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setReadOnly(True)
        self._process = QtCore.QProcess()
        self._process.readyReadStandardOutput.connect(self.handle_stdout)
        self._process.readyReadStandardError.connect(self.handle_stderr)

    def start_log(self, program, arguments=None):
        if arguments is None:
            arguments = []
        self._process.start(program, arguments)

    def add_log(self, message):
        self.appendPlainText(message.rstrip())

    def handle_stdout(self):
        message = self._process.readAllStandardOutput().data().decode()
        self.add_log(message)

    def handle_stderr(self):
        message = self._process.readAllStandardError().data().decode()
        self.add_log(message)


if __name__ == "__main__":

    import sys

    app = QtWidgets.QApplication(sys.argv)

    w = LogView()
    w.resize(640, 480)
    w.show()
    w.start_log("adb", ["logcat", "*:I"])

    sys.exit(app.exec_())

推荐阅读