Skip to content

Instantly share code, notes, and snippets.

@olih
Created August 9, 2013 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olih/6193866 to your computer and use it in GitHub Desktop.
Save olih/6193866 to your computer and use it in GitHub Desktop.
List all the linux/MacOs processes (ps -A) Kill all the processes with a given name
#!/usr/bin/env python
# encoding: utf-8
"""
Executes a ps
Kill all processes with a given name
Creator: 2013, Olivier Huin (https://github.com/olih)
License: Eclipse Public License - v 1.0
Contributors:
"""
import sys
import os
import subprocess, signal
import shlex
import string
def ps():
r=[]
command_line='ps -A -o "pid %cpu user %mem command"'
args = shlex.split(command_line)
p = subprocess.Popen(args, stdout=subprocess.PIPE)
out, err = p.communicate()
alllines=out.splitlines()
lines=alllines[1:] #skip header
for line in lines:
[pid_str,cpu_str,user,mem_str,command]=string.split(line,None,4)
pid=int(pid_str)
cpu=float(cpu_str)
mem=float(mem_str)
info=[pid,cpu,mem,user,command]
r.append(info)
return r
#Search a term in the list of commands
def search(term):
r=[]
all=ps()
for p in all:
[pid,cpu,mem,user,command]=p
if term in command:
r.append(p)
return r
#Kill all the processes with term
def kill(term):
all= search(term)
if not all or all==[]:
return "No processes"
for p in all:
[pid,cpu,mem,user,command]=p
print "killing %s %s" % (pid,command)
os.kill(pid, signal.SIGKILL)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment