Kill exe from the command line in windows if its running

pysup 0 Tallied Votes 217 Views Share

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)
Tech B 48 Posting Whiz in Training

This looks good. I read a little about killing processes in Gray Hat Python via PID. There is another way too with WMI(http://www.daniweb.com/forums/thread245419.html)

I used it to kill the internet, but could be used for other things like notepad. Mine was set to kill the process at a certain time.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.