PyQt:多个 QProcess 和输出 [英] PyQt: Multiple QProcess and output

查看:83
本文介绍了PyQt:多个 QProcess 和输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

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

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.

推荐答案

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

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

这篇关于PyQt:多个 QProcess 和输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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