Skip to content

Instantly share code, notes, and snippets.

@stanistan
Created October 2, 2012 20:33
Show Gist options
  • Save stanistan/3823100 to your computer and use it in GitHub Desktop.
Save stanistan/3823100 to your computer and use it in GitHub Desktop.
kill-ps
#!/usr/bin/env python
"""
Use this to kill hanging processes that don't have a specific name,
greps for the name in the process name, and kills -9 by PID
"""
import subprocess
import re
import optparse
import sys
def runBash(cmd):
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
return p.stdout.read().strip().split("\n")
def getProcesses(name):
command = "ps | grep " + name
def filterPy(line):
line = line.strip()
return len(line) > 0 and not bool(re.search('grep|python', line))
def processFromPS(line):
return re.search('\d+', line).group(0)
return map(processFromPS, filter(filterPy, runBash(command)))
def killProcesses(ps, name):
if not len(ps):
print "-- nothing to kill for " + name
for p in ps:
print("-- killing [" + name + "] process [" + p + "]")
print(runBash("kill -9 " + p))
def main():
p = optparse.OptionParser()
opts, args = p.parse_args()
if not len(args):
sys.stderr.write('No process name to kill given!\n')
for f in args:
killProcesses(getProcesses(f), f)
if __name__ == '__main__':
main()
@stanistan
Copy link
Author

Put this somewhere in your path, allow executable, (chmod + x).

Usage:

kill-ps lein

I mostly use this to kill lein processes.

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