我有一个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

最佳答案

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

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

关于python - PyQt:多个QProcess和输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50930792/

10-12 17:03