我使用PyQt5在Python 3.8中开发应用。
我需要运行并能够杀死与PyQT表单不同的进程。 当我使用 process.start 然后使用 process.kill 时,它会终止该进程。
但是当我使用process.startDetached()
时,process.kill()
不起作用。
下面是一个示例:
from form import Ui_MainWindow
from PyQt5 import QtWidgets
class myapp(QtWidgets.QMainWindow):
def __init__(self):
super(myapp, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.process = QProcess(self)
self.ui.pushButton.clicked.connect(self.btnClicked)
self.ui.pushButton_2.clicked.connect(self.process.kill)
def btnClicked(self):
runstr = 'ping'
args = ['localhost','-t']
self.process.startDetached(runstr, args)
app = QtWidgets.QApplication([])
application = myapp()
application.show()
sys.exit(app.exec())
您能否建议如何以分离模式杀死进程。
答案 0 :(得分:0)
启动分离的进程时,QProcess无法终止该进程,因此在这些情况下,您必须获取子进程的pid,并使用OS方法将其终止,如以下问题的答案所示:>
from PyQt5 import QtCore, QtWidgets
import psutil
from form import Ui_MainWindow
class MyApp(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MyApp, self).__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.process = QtCore.QProcess(self)
self.ui.pushButton.clicked.connect(self.start_process)
self.ui.pushButton_2.clicked.connect(self.stop_process)
self._pid = -1
@QtCore.pyqtSlot()
def start_process(self):
runstr = "ping"
args = ["localhost", "-t"]
self.process.setProgram(runstr)
self.process.setArguments(args)
ok, pid = self.process.startDetached()
if ok:
self._pid = pid
@QtCore.pyqtSlot()
def stop_process(self):
if self._pid > 0:
p = psutil.Process(self._pid)
p.terminate()
self._pid = -1
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
application = MyApp()
application.show()
sys.exit(app.exec_())