Pyside: Multiple QProcess output to TextEdit

2019-08-03 16:41发布

问题:

I have a pyside app that calls an exectuable. I want to run this executable asynchronously in n processes and capture the output of each process in a QTextEdit.

At the moment I have:

def run(self, args, worklist):        

    self.viewer = OutputDialog(self)

    self.procs = []
    for path in worklist:
        final_args = args + path

        p = QtCore.QProcess(self)
        p.readyReadStandardOutput.connect(self.write_process_output)
        self.procs.append(p)
        p.start(self.exe, final_args)

def write_process_output(self):
    for p in self.procs:
        self.viewer.text_edit.append(p.readAllStandardOutput())

Which is way too clunky as each time a process sends the 'ready' signal, it attempts to get the output for ALL processes.

How can I get the output just for the process that sent the signal?

回答1:

Connect the signal using a lambda so that the relevant process is passed to the slot:

        p.readyReadStandardOutput.connect(
            lambda process=p: self.write_process_output(process))


    def write_process_output(self, process):
        self.viewer.text_edit.append(process.readAllStandardOutput())