PyQt:多个QProcess和输出

时间:2018-06-19 14:24:16

标签: python pyqt pyqt4 qprocess

我有一个PyQt窗口,该窗口将多个可执行文件称为QProcess。在最后一个过程完成后,如何列出每个过程的输出? (类似于process_result = [“ result1”,“ result2”,..]) 让我们说它看起来像这样:

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

我可以用process.readyReadStandardOutput()进行读取,但是由于进程并行运行,因此非常混乱。 process.waitForFinished()不起作用,因为GUI将冻结。 另外,我检查了以下有关多线程的页面:Multithreading PyQt applications with QThreadPool。另一个问题类似,但也没有帮助我:Pyside: Multiple QProcess output to TextEdit

1 个答案:

答案 0 :(得分:1)

一种可行的解决方案是创建一个管理进程的类,并在所有进程按照您的要求完成时发出单个信号。

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_())