|
| 1 | +from typing import Optional, Sequence |
| 2 | + |
| 3 | +from PySide6 import QtCore |
| 4 | + |
| 5 | + |
| 6 | +class QSubProcessTool(QtCore.QObject): |
| 7 | + """辅助使用QProcess创建并管理子进程的工具类""" |
| 8 | + |
| 9 | + # 自定义信号,参数为 (output_type: QSubProcessTool.output_type, output_text: str) |
| 10 | + output = QtCore.Signal(tuple) |
| 11 | + |
| 12 | + # output_types |
| 13 | + STATE = 0 |
| 14 | + FINISHED = 1 |
| 15 | + STDOUT = 2 |
| 16 | + STDERR = 3 |
| 17 | + |
| 18 | + def __init__(self, parent: Optional[QtCore.QObject] = None) -> None: |
| 19 | + super(QSubProcessTool, self).__init__(parent) |
| 20 | + self.process: Optional[QtCore.QProcess] = None |
| 21 | + |
| 22 | + def start_process(self, program: str, arguments: Sequence[str]) -> None: |
| 23 | + """ |
| 24 | + 启动子进程 \n |
| 25 | + :param program: 子进程命令 |
| 26 | + :param arguments: 子进程参数 |
| 27 | + :return: None |
| 28 | + """ |
| 29 | + |
| 30 | + if self.process is None: # 防止在子进程运行结束前重复启动 |
| 31 | + self.process = QtCore.QProcess() |
| 32 | + |
| 33 | + self.process.readyReadStandardOutput.connect(self._handle_stdout) # type: ignore |
| 34 | + self.process.readyReadStandardError.connect(self._handle_stderr) # type: ignore |
| 35 | + self.process.stateChanged.connect(self._handle_state) # type: ignore |
| 36 | + self.process.finished.connect(self._process_finished) # type: ignore |
| 37 | + |
| 38 | + self.process.start(program, arguments) |
| 39 | + |
| 40 | + def _process_finished(self) -> None: |
| 41 | + """ |
| 42 | + 处理子进程的槽 \n |
| 43 | + :return: None |
| 44 | + """ |
| 45 | + self.output.emit((self.FINISHED, "Subprocess finished.")) |
| 46 | + self.process = None |
| 47 | + |
| 48 | + def _handle_stdout(self) -> None: |
| 49 | + """ |
| 50 | + 处理标准输出的槽 \n |
| 51 | + :return: None |
| 52 | + """ |
| 53 | + |
| 54 | + if self.process: |
| 55 | + data = self.process.readAllStandardOutput() |
| 56 | + stdout = bytes(data).decode("utf8") |
| 57 | + self.output.emit((self.STDOUT, stdout)) |
| 58 | + |
| 59 | + def _handle_stderr(self) -> None: |
| 60 | + """ |
| 61 | + 处理标准错误的槽 \n |
| 62 | + :return: None |
| 63 | + """ |
| 64 | + |
| 65 | + if self.process: |
| 66 | + data = self.process.readAllStandardError() |
| 67 | + stderr = bytes(data).decode("utf8") |
| 68 | + self.output.emit((self.STDERR, stderr)) |
| 69 | + |
| 70 | + def _handle_state(self, state: QtCore.QProcess.ProcessState) -> None: |
| 71 | + """ |
| 72 | + 将子进程运行状态转换为易读形式 \n |
| 73 | + :param state: 进程运行状态 |
| 74 | + :return: None |
| 75 | + """ |
| 76 | + |
| 77 | + states = { |
| 78 | + QtCore.QProcess.NotRunning: "Not running", |
| 79 | + QtCore.QProcess.Starting: "Starting", |
| 80 | + QtCore.QProcess.Running: "Running", |
| 81 | + } |
| 82 | + state_name = states[state] |
| 83 | + self.output.emit((self.STATE, state_name)) |
0 commit comments