Printing QProcess Stdout only if it contains a Substring

夙愿已清 提交于 2021-02-10 16:01:36

问题


A PyQt4 app runs ping in a QProcess. A QTextEdit named self.output will output everything from ping. A second QTextEdit named self.summary will only output the line if it contains the string TTL.

Problem: I have managed to get self.output working but not self.summary as I am not sure how to write its code in the dataReady function. Any ideas?

import sys
from PyQt4 import QtGui, QtCore


class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.initUI()


    def dataReady(self):
        cursorOutput = self.output.textCursor()
        cursorSummary = self.summary.textCursor()

        cursorOutput.movePosition(cursorOutput.End)
        cursorSummary.movePosition(cursorSummary.End)

        processStdout = str(self.process.readAll())

        # Update self.output
        cursorOutput.insertText(processStdout)

        # Update self.summary
        for line in processStdout:
            if 'TTL' in line:
                cursorSummary.insertText(line)


        self.output.ensureCursorVisible()
        self.summary.ensureCursorVisible()


    def callProgram(self):
        self.process.start('ping', ['127.0.0.1'])


    def initUI(self):
        layout = QtGui.QHBoxLayout()
        self.runBtn = QtGui.QPushButton('Run')
        self.runBtn.clicked.connect(self.callProgram)

        self.output = QtGui.QTextEdit()
        self.summary = QtGui.QTextEdit()

        layout.addWidget(self.runBtn)
        layout.addWidget(self.output)
        layout.addWidget(self.summary)

        centralWidget = QtGui.QWidget()
        centralWidget.setLayout(layout)
        self.setCentralWidget(centralWidget)

        # QProcess object for external app
        self.process = QtCore.QProcess(self)
        self.process.readyRead.connect(self.dataReady)
        self.process.started.connect(lambda: self.runBtn.setEnabled(False))
        self.process.finished.connect(lambda: self.runBtn.setEnabled(True))


def main():
    app = QtGui.QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

回答1:


One problem that you could have is that each output of QProcess could have several lines, ie contain "\n", to not have that problem we separate it, and then we do the search:

for line in processStdout.split("\n"):
    if "TTL" in line:
        cursorSummary.insertText(line+"\n")

In your initial code you are getting each character with the for loop, which is generating the error.

Note: In linux I have to filter by the word ttl. In addition to changing the QProcess to: self.process.start('ping', ['-c', '3', '127.0.0.1'])



来源:https://stackoverflow.com/questions/45087825/printing-qprocess-stdout-only-if-it-contains-a-substring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!