[python] Kill process by name?

I'm trying to kill a process (specifically iChat). On the command line, I use these commands:

ps -A | grep iChat 

Then:

kill -9 PID

However, I'm not exactly sure how to translate these commands over to Python.

This question is related to python process kill

The answer is


For me the only thing that worked is been:

For example

import subprocess
proc = subprocess.Popen(["pkill", "-f", "scriptName.py"], stdout=subprocess.PIPE)
proc.wait()

The Alex Martelli answer won't work in Python 3 because out will be a bytes object and thus result in a TypeError: a bytes-like object is required, not 'str' when testing if 'iChat' in line:.

Quoting from subprocess documentation:

communicate() returns a tuple (stdout_data, stderr_data). The data will be strings if streams were opened in text mode; otherwise, bytes.

For Python 3, this is solved by adding the text=True (>= Python 3.7) or universal_newlines=True argument to the Popen constructor. out will then be returned as a string object.

import subprocess, signal
import os

p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE, text=True)
out, err = p.communicate()

for line in out.splitlines():
    if 'iChat' in line:
        pid = int(line.split(None, 1)[0])    
        os.kill(pid, signal.SIGKILL)

Alternatively, you can create a string using the decode() method of bytes.

import subprocess, signal
import os

p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
out, err = p.communicate()

for line in out.splitlines():
    if 'iChat' in line.decode('utf-8'):
        pid = int(line.split(None, 1)[0])    
        os.kill(pid, signal.SIGKILL)

you can use WMI module to do this on windows, though it's a lot clunkier than you unix folks are used to; import WMI takes a long time and there's intermediate pain to get at the process.


this worked for me in windows 7

import subprocess
subprocess.call("taskkill /IM geckodriver.exe")

Get the process object using the Process.

>>> import psutil
>>> p = psutil.Process(23442)
>>> p
psutil.Process(pid=23442, name='python3.6', started='09:24:16')
>>> p.kill()
>>> 

If you have killall:

os.system("killall -9 iChat");

Or:

os.system("ps -C iChat -o pid=|xargs kill -9")

You can use pkill <process_name> in a unix system to kill process by name.

Then the python code will be:

>>> import os
>>> process_name=iChat
>>> os.system('pkill '+process_name)

psutil can find process by name and kill it:

import psutil

PROCNAME = "python.exe"

for proc in psutil.process_iter():
    # check whether the process name matches
    if proc.name() == PROCNAME:
        proc.kill()

If you want to kill the process(es) or cmd.exe carrying a particular title(s).

import csv, os
import subprocess
# ## Find the command prompt windows.
# ## Collect the details of the command prompt windows and assign them.
tasks = csv.DictReader(subprocess.check_output('tasklist /fi "imagename eq cmd.exe" /v /fo csv').splitlines(), delimiter=',', quotechar='"')
# ## The cmds with titles to be closed.
titles= ["Ploter", "scanFolder"]

# ## Find the PIDs of the cmds with the above titles.
PIDList = []
for line in tasks:
    for title in titles:
        if  title in line['Window Title']:
           print line['Window Title']       
           PIDList.append(line['PID'])

# ## Kill the CMDs carrying the PIDs in PIDList
for id in PIDList:
    os.system('taskkill /pid ' + id ) 

Hope it helps. Their might be numerous better solutions to mine.


The below code will kill all iChat oriented programs:

p = subprocess.Popen(['pgrep', '-l' , 'iChat'], stdout=subprocess.PIPE)
out, err = p.communicate()

for line in out.splitlines():        
    line = bytes.decode(line)
    pid = int(line.split(None, 1)[0])
    os.kill(pid, signal.SIGKILL)

If you have to consider the Windows case in order to be cross-platform, then try the following:

os.system('taskkill /f /im exampleProcess.exe')

In the same style as Giampaolo RodolĂ ' answer but as one liner, case insensitive and without having to match the whole process name, in windows you would have to include the .exe suffix.

[x.kill() for x in psutil.process_iter() if 'ichat' in x.name().lower()]

import psutil
pid_list=psutil.get_pid_list()
print pid_list
p = psutil.Process(1052)
print p.name
for i in pid_list:
    p = psutil.Process(i)
    p_name=p.name
    print str(i)+" "+str(p.name)
    if p_name=="PerfExp.exe":
        print "*"*20+" mam ho "+"*"*20
        p.kill()

import os, signal

def check_kill_process(pstring):
    for line in os.popen("ps ax | grep " + pstring + " | grep -v grep"):
        fields = line.split()
        pid = fields[0]
        os.kill(int(pid), signal.SIGKILL)

You can try this. but before you need to install psutil using sudo pip install psutil

import psutil
for proc in psutil.process_iter(attrs=['pid', 'name']):
    if 'ichat' in proc.info['name']:
        proc.kill()

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to process

Fork() function in C How to kill a nodejs process in Linux? Xcode process launch failed: Security Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes Linux Script to check if process is running and act on the result CreateProcess error=2, The system cannot find the file specified How to make parent wait for all child processes to finish? How to use [DllImport("")] in C#? Visual Studio "Could not copy" .... during build How to terminate process from Python using pid?

Examples related to kill

How to kill a nodejs process in Linux? What does 'killed' mean when a processing of a huge CSV with Python, which suddenly stops? how to kill hadoop jobs Why number 9 in kill -9 command in unix? How to kill a process on a port on ubuntu How to kill a child process by the parent process? How to kill all processes matching a name? How do I kill an Activity when the Back button is pressed? Terminating idle mysql connections How can I stop a running MySQL query?