python - 如何在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'))
解决方案
您必须使用 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_())
推荐阅读
- cloud - 二维码播放视频
- pic - 我不知道我是否为 PIC24F 正确初始化 ADC
- git - GIT Repo 错误:无法推送到远程存储库
- javascript - Sonarqube 问题“重构此方法以将其认知复杂度从 18 降低到允许的 15。” 重写代码块
- math - 如何减去两个正的 IEEE-754 数字?
- mule - Mule 支持 CDC 和 Streaming
- checkbox - 谷歌表格 - 只允许在范围内选中一个复选框
- hash - 如何在不使用指针的情况下维护哈希链接?
- image - 反转部分(复选框) Shopify
- pandas - 使用 Python 字典过滤 pandas df 中的唯一匹配项