1

I develop app in Python 3.8 with PyQt5.

I need to run and able to kill a separate process from the PyQT Form. When I use process.start and then process.kill it kills the process.

But when I use process.startDetached() then process.kill() doesn't work.

Below is an example:

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())

Could you advise the way how to kill a process in detached mode.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
VladimirB
  • 25
  • 4
  • Please add import sys in example and use class Ui_MainWindow from example from https://github.com/VovaBobyr/PythonLearning/blob/master/BackgroundRun/form.py – VladimirB Feb 05 '20 at 14:43

1 Answers1

1

When you launch a detached process then the QProcess cannot kill the process, so in these cases you must obtain the pid of the child process and use the OS methods to kill it as indicated in the answers to the following questions:

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_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241