Is it possible to kill a process on Windows from within Python?

PythonWindowsWindows Xp

Python Problem Overview


I'm using Python 2.6. Sometimes there become several instances of a certain process open, and that process causes some problems in itself. I want to be able to programatically detect that there are multiple instances of that process and to kill them.

For example, maybe in some cases there are 50 instances of make.exe open. I want to be able to tell that there are 20 instances open, and to kill them all. How is this accomplished?

Python Solutions


Solution 1 - Python

I would think you could just use taskkill and the Python os.system()

import os
os.system("taskkill /im make.exe")

Note: I would just note you might have to fully qualify the taskkill path. I am using a Linux box so I can't test...

Solution 2 - Python

Yes,You can do it

import os
os.system("taskkill /f /im  Your_Process_Name.exe")
  1. /f : Specifies that process(es) be forcefully terminated.
  2. /im (ImageName ): Specifies the image name of the process to be terminated.
  3. For more info regarding TaskKill

Solution 3 - Python

There is a nice cross-platform python utility psutil that exposes a kill() routine on a processes that can be listed with psutil.process_iter().

There is already an example in the other thread: https://stackoverflow.com/a/4230226/4571444

Solution 4 - Python

You can use the TerminateProcess of the win32 api to kill a process. See the following example : http://code.activestate.com/recipes/347462-terminating-a-subprocess-on-windows/

You need to give it a process handle. If the process is started from your code, the process handle is returned by the CreateProcess or popen.

If the process was started by something else, you need to get this handle you can use EnumProcess or WMI to retrieve it.

Solution 5 - Python

How about this, I tested it with ActiveState Python 2.7:

import sys, traceback, os

def pkill (process_name):
    try:
        killed = os.system('tskill ' + process_name)
    except Exception, e:
        killed = 0
    return killed

call it with:

pkill("program_name")

Solution 6 - Python

I think the code is like this will work:

import os

def terminate(ProcessName):
    os.system('taskkill /IM "' + ProcessName + '" /F')

terminate('chrome.exe')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncupofView Question on Stackoverflow
Solution 1 - PythonNixView Answer on Stackoverflow
Solution 2 - PythonAvinash JeevaView Answer on Stackoverflow
Solution 3 - PythonPshemy108View Answer on Stackoverflow
Solution 4 - PythonlucView Answer on Stackoverflow
Solution 5 - PythonGiovanniView Answer on Stackoverflow
Solution 6 - PythonMkritaView Answer on Stackoverflow