【问题标题】:Kill program generated by subprocess with PyQt5使用 PyQt5 杀死子进程生成的程序
【发布时间】:2020-03-05 14:57:23
【问题描述】:

这是一个为解释示例而创建的程序。

ma​​in.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

我想在单击kill按钮时杀死由子进程生成的程序。换句话说,我想向程序发送一个终止信号,比如按 CTRL+C。

当PyQt5主程序终止时,我希望子进程生成的程序也终止。

我该怎么做?

请帮我解决这个问题。

【问题讨论】:

  • 使用Popen有什么具体原因,或者可以用QProcess代替吗?
  • 我是菜鸟,所以我不了解 QProcess。这就是我想做的。
  • 1.运行shell命令,实时获取stdout、stderr。
  • 2.运行批处理文件,实时获取stdout、stderr,并可停止文件执行。
  • 3.运行其他应用程序并可以杀死它。

标签: python pyqt5 kill-process


【解决方案1】:

终于找到方法了。

我使用了psutil 模块。

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

pip 安装 psutil

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多