首页 > 解决方案 > Kill program generated by subprocess with PyQt5

问题描述

This is a program created as an example for explanation.

main.py

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QPushButton
from worker import Worker


class TestUI(QWidget):
    def __init__(self):
        super().__init__()

        self.worker = Worker()

        self.init_ui()

    def init_ui(self):
        run_btn = QPushButton("Run")
        run_btn.clicked.connect(self.run)

        kill_btn = QPushButton("Kill")
        kill_btn.clicked.connect(self.kill)

        layout = QGridLayout()
        layout.addWidget(run_btn, 0, 0)
        layout.addWidget(kill_btn, 0, 1)
        self.setLayout(layout)

    def run(self):
        self.worker.run_command("calc.exe")

    def kill(self):
        self.worker.kill_command()


if __name__ == "__main__":
    APP = QApplication(sys.argv)
    ex = TestUI()
    ex.show()
    sys.exit(APP.exec_())

worker.py

import os
import signal
import subprocess
from PyQt5.QtCore import QObject


class Worker(QObject):
    def __init__(self):
        super().__init__()

    def run_command(self, cmd):
        self.proc = subprocess.Popen(cmd)

    def kill_command(self):
        # self.proc.kill() => Not working
        # self.proc.terminate() => Not working
        # os.kill(self.proc.pid, signal.SIGTERM) => Not working

I want to kill the program generated by subprocess when I click the kill button. In other words, I want to send a kill signal to the program like pressing CTRL+C.

And when the main PyQt5 program is terminated, I want the program generated by subprocess to terminate as well.

How can I do this?

Please help me with this problem.

标签: pythonpyqt5kill-process

解决方案


最后,我找到了方法。

我使用了一个psutil模块。

这不是内置模块。所以你需要先安装它。

点安装 psutil

而且,现在您可以像下面一样使用这个模块。

def kill_command(self):
    for proc in psutil.process_iter():
        if "calc" in proc.name().lower():
            os.kill(proc.pid, signal.SIGTERM)

推荐阅读