Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python script to kill a process by its name
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)
@c446984928
Copy link

c446984928 commented Sep 6, 2015

def check_kill_process(pstring):
"""
find process by name and kill it
:param pstring: name of the process you want to find and kill
"""
out = commands.getoutput("ps ax | grep " + pstring + " | grep -v grep").split("\n")
for line in out:
fields = line.split()
pid = fields[0]
os.kill(int(pid), signal.SIGKILL)

@tusharmakkar08
Copy link

tusharmakkar08 commented Jul 21, 2016

I feel using psutil is better.

@abelpc
Copy link

abelpc commented Oct 4, 2016

'psutil' is not always 'util' for interactive processes called by bash scripts, for example. The above script takes this into consideration, killing them, but not mistakenly killing a random '/bin/bash', for example..

@scriptedp0ison
Copy link

scriptedp0ison commented Mar 16, 2017

or you could just import the subprocess module, have the user enter a string based input, convert it to int, then via the sys module [ sys.stdin.readline()] or raw_input depending on the version of python, then create a variable to store the input with the 'killall' command, through the subprocess.call() function

@ryancasler
Copy link

ryancasler commented Apr 26, 2018

Where do you list the name of the process you want to kill?!?!?! OMG....I've been searching for an hour!!!!

@ageron
Copy link

ageron commented Jan 16, 2019

You can use psutil's process_iter() to list processes, and use each process's name() and cmdline() method to get its name and command line arguments.
For example, this gist implements a few functions that list processes by name or by filtering on their command line arguments.

@datalifenyc
Copy link

datalifenyc commented Mar 19, 2020

@marcoagner Perfect solution for my selenium issue with driver.quit() not terminating chromedriver.

macOS: Catalina  
Python: 3.7.4
ChromeDriver: 80.0.3987.106

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment