python - 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.
解决方案
最后,我找到了方法。
我使用了一个psutil
模块。
这不是内置模块。所以你需要先安装它。
点安装 psutil
而且,现在您可以像下面一样使用这个模块。
def kill_command(self):
for proc in psutil.process_iter():
if "calc" in proc.name().lower():
os.kill(proc.pid, signal.SIGTERM)
推荐阅读
- floating-point - 双数的表示
- c# - 如何使用线程在 VS 中移动 Powerpack Ovalshape
- r - 用颜色渐变绘制 geom_segment 线?(或者还有另一种强调开始与结束的方法吗?)
- c# - 动态添加的面板总是将索引设为 0
- python - 如何使用python按一定大小过滤和列出s3文件夹中的所有对象
- r - 用for循环输出填充矩阵
- javascript - 我如何在这里关闭我的覆盖模式框,它不起作用
- python - 正则表达式适用于 Sublime,而不适用于 Python (Jupyter)
- python - 如何使用堆栈跟踪来告诉我应该为 Python 的 try/except 使用哪个异常
- php - PHP - 使用 2 个外键将数据插入 MySQL 表