#!/usr/bin/python

# killpython.py
"""
This script looks for all processes where python is running a script, and kills only those
where the script is one of the command line arguments.  The path to the script is irrelevant,
only the script name should be supplied on the command line.
Ex: "killpython.py multimon.py lux.py calibmon.py" would kill multimon, lux and calibmon.
"""

returnValue=0				# if non-zero, indicates failure to kill process
import os,sys

killList=sys.argv[1:]			# these are python scripts that should be killed
if len(killList)==0:
	sys.exit(0)

processList=os.listdir("/proc")		# this is supported on linux as a way to get process info

for process in processList:
	try:
		pid=int(process)
		f=file("/proc/"+process+"/cmdline")
		cmdLine=f.read()
		f.close()
		tokens=cmdLine.split("\x00")
		if len(tokens)>2:					# at least one arg after cmd
			cmdPath=tokens[0]				# here's the command itself
			cmdPathTokens=cmdPath.split("/")		# separate path into bits
			cmd=cmdPathTokens[len(cmdPathTokens)-1]		# cmd without path prefix
			arg1=tokens[1]					# here's the first arg
			arg1Tokens=arg1.split("/")			# also separate path if any
			argEnding=arg1Tokens[len(arg1Tokens)-1]		# arg1 with no path prefix
			if (cmd=="python") and (argEnding in killList):
				print "killing process "+process+": "+cmdLine.replace("\x00"," ")	# replace nulls with spaces
				flag=os.system("kill -9 "+process)
				if flag!=0:
					print "kill failed, exit code="+`flag`
					returnValue=flag;
	except ValueError:
		pid=0	# some "files" in the /proc pseudo-directory are not integer pid's

sys.exit(returnValue)
