from PySide6.QtCore import QObject, Signal from threading import Thread import subprocess class ProcManager(QObject): process_terminated = Signal(int, str) def __init__(self) -> None: super(ProcManager, self).__init__() self.thre = None self.proc = None def start(self, proc): # this method might override the old process and thread self.proc = proc self.thre = Thread(target=self.detect_end) self.thre.start() def stop(self): if self.proc: self.proc.terminate() try: self.proc.wait(1) except subprocess.TimeoutExpired as e: self.proc.kill() if self.thre: self.thre.join() self.thre = None def detect_end(self): # wait for the process to terminate while True: try: self.proc.wait(1) break except subprocess.TimeoutExpired as e: continue returncode = self.proc.returncode errorstream = self.proc.stderr.read() if isinstance(errorstream, bytes): errorstream = errorstream.decode('utf-8') self.proc = None print('Process Terminated:', returncode, errorstream) self.process_terminated.emit(returncode, errorstream)