Start New Discussion within our Software Development Community

Hi,

The code below will check if a particular exe is running in windows, return the Process ID and force kill the process. If anybody has an easier way to do it please feel free to comment :)

def isrunning(exe) :

        try :
                p = os.popen(r'tasklist /FI "IMAGENAME eq "'+ exe + ' /FO "LIST" 2>&1' , 'r' )
                PID = p.read().split('\n')[2].split(":")[1].lstrip(" ")
                p.close()
                return PID

        except :
                p.close()
                return "None"


#Usage

PID = isrunning('notepad.exe')

if PID != "None" :
        os.system(r'taskkill /F /PID ' + PID)