how to kill a process in Windows using Python

While checking some facts for my previous post “how to find a process by name in Windows using Python” I came across a post about “how to kill a process in Windows using Python“.  I realize I have code for an alternate approach to doing such a thing so figured I’d post a sequel.

Once you have the process identifier in hand using the method described in my previous post, you can get the handle to the process like this (assume pid is the process identifier returned by GetProcessID):


import win32api, win32con

handle = win32api.OpenProcess( win32con.PROCESS_TERMINATE, 0, pid )

If you already have the handle (e.g., if you had started the process in the same bit of code as Rajkumar did in his blog), then you can go straight to terminating the process:


win32api.TerminateProcess( handle, 0 )

win32api.CloseHandle( handle )

I’m not sure of the context in which the other author needed to kill a process, so the approach may not fit his needs.  Anyway, it’s an alternative in case anyone’s looking….

That’s all, hope it helps!

Advertisement

About this entry