【问题标题】:How to print console output in pyQt如何在pyQt中打印控制台输出
【发布时间】:2020-09-11 10:30:54
【问题描述】:

我需要在 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'))

【问题讨论】:

  • 不,您不一定需要线程。但是这部分没有意义,self.textBrowser.setText(subprocess.run('result.stdout'))

标签: python pyqt adb


【解决方案1】:

您必须使用 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_())

【讨论】:

    猜你喜欢
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 2022-01-09
    • 1970-01-01
    • 2012-06-01
    相关资源
    最近更新 更多