PyQt: Multiple QProcess and output

时光总嘲笑我的痴心妄想 提交于 2021-02-08 03:38:55

问题


I have a PyQt window that calls multiple executables as QProcess. How can I list the outputs of each process after the last one has finished? (something like process_result = ["result1", "result2",..]) Let us say it looks like this:

for i in list_of_processes:
    process = QtCore.QProcess()
    process.start(i)

I can read with process.readyReadStandardOutput() somehow but it is quite chaotic because processes run parallel. process.waitForFinished() does not work because the GUI will freeze. Also, I checked following page about multithreading: Multithreading PyQt applications with QThreadPool. Another question is similar but did not help me either: Pyside: Multiple QProcess output to TextEdit.


回答1:


A possible solution is to create a class that manages the processes, and that emits a single signal when all the processes finish as you require.

import sys

from functools import partial

from PyQt4 import QtCore, QtGui


class TaskManager(QtCore.QObject):
    resultsChanged = QtCore.pyqtSignal(list)

    def __init__(self, parent=None):
        QtCore.QObject.__init__(self, parent)
        self.results = []
        self.m_processes = []
        self.number_process_running = 0

    def start_process(self, programs):
        for i, program in enumerate(programs):
            process = QtCore.QProcess(self)
            process.readyReadStandardOutput.connect(partial(self.onReadyReadStandardOutput, i))
            process.start(program)
            self.m_processes.append(process)
            self.results.append("")
            self.number_process_running += 1

    def onReadyReadStandardOutput(self, i):
        process = self.sender()
        self.results[i] = process.readAllStandardOutput()
        self.number_process_running -= 1
        if self.number_process_running <= 0:
            self.resultsChanged.emit(self.results)

def on_finished(results):
    print(results)
    QtCore.QCoreApplication.quit()

if __name__ == '__main__':
    app = QtCore.QCoreApplication(sys.argv)
    manager = TaskManager()
    manager.start_process(["ls", "ls"])
    manager.resultsChanged.connect(on_finished)
    sys.exit(app.exec_())


来源:https://stackoverflow.com/questions/50930792/pyqt-multiple-qprocess-and-output

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