How to get the pid of the process started by subprocess.run and kill it

Viewed 3389

I'm using Windows 10 and Python 3.7.

I ran the following command.

import subprocess
exeFilePath = "C:/Users/test/test.exe"
subprocess.run(exeFilePath)

The .exe file launched with this command, I want to force-quit when the button is clicked or when the function is executed.

Looking at a past question, it has been indicated that the way to force quit is to get a PID and do an OS.kill as follows.

import signal
os.kill(self.p.pid, signal.CTRL_C_EVENT)

However, I don't know how to get the PID of the process started in subprocess.run.

What should I do?

1 Answers

Assign a variable to your subprocess

import os
import signal
import subprocess

exeFilePath = "C:/Users/test/test.exe"
p = subprocess.Popen(exeFilePath)
print(p.pid) # the pid
os.kill(p.pid, signal.SIGTERM) #or signal.SIGKILL 

In same cases the process has children processes. You need to kill all processes to terminate it. In that case you can use psutil

#python -m pip install —user psutil 

import psutil

#remember to assign subprocess to a variable 

def kills(pid):
    '''Kills all process'''
    parent = psutil.Process(pid)
    for child in parent.children(recursive=True):
        child.kill()
    parent.kill()

#assumes variable p
kills(p.pid)

This will kill all processes in that PID

Related