从控制台实时打印输出到 QTextEdit [英] Printing Output from Console Live To QTextEdit

查看:67
本文介绍了从控制台实时打印输出到 QTextEdit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在尝试(实时)更新带有 shell 输出的 QTextEdit :

so I am trying to (live) update a QTextEdit with shell output as such:

txtDirb = QTextEdit()
dirb_command = "dirb" + " " + url
p = subprocess.Popen([dirb_command], stdout=subprocess.PIPE, shell=True)
out = p.stdout.read()
txtDirb.append(str(out)) # buggy!

当然这不会实时更新,而是等待整个命令执行然后填充QTextEdit.有没有办法实现实时更新?

Of course this does not update live, instead waits for the whole command to execute and then fills the QTextEdit. Is there a way to achieve live update?

谢谢.

推荐答案

不要使用 subprocess.Popen() 因为它是阻塞的,它只在执行结束时给你结果,而是使用 QProcess:

Do not use subprocess.Popen() since it is blocking and it only gives you the result at the end of the execution, instead use QProcess:

import sys

from PyQt5 import QtCore, QtWidgets


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.process = QtCore.QProcess(self)
        self.process.setProgram("dirb")
        self.process.setProcessChannelMode(QtCore.QProcess.MergedChannels)

        self.lineedit = QtWidgets.QLineEdit("http://webscantest.com")
        self.button = QtWidgets.QPushButton("Start")
        self.textedit = QtWidgets.QTextEdit(readOnly=True)

        lay = QtWidgets.QGridLayout(self)
        lay.addWidget(self.lineedit, 0, 0)
        lay.addWidget(self.button, 0, 1)
        lay.addWidget(self.textedit, 1, 0, 1, 2)

        self.button.clicked.connect(self.on_clicked)
        self.process.readyReadStandardOutput.connect(self.on_readyReadStandardOutput)
        self.process.finished.connect(self.on_finished)

    @QtCore.pyqtSlot()
    def on_clicked(self):
        if self.button.text() == "Start":
            self.textedit.clear()
            self.process.setArguments([self.lineedit.text()])
            self.process.start()
            self.button.setText("Stop")
        elif self.button.text() == "Stop":
            self.process.kill()

    @QtCore.pyqtSlot()
    def on_readyReadStandardOutput(self):
        text = self.process.readAllStandardOutput().data().decode()
        self.textedit.append(text)

    @QtCore.pyqtSlot()
    def on_finished(self):
        self.button.setText("Start")


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

这篇关于从控制台实时打印输出到 QTextEdit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆