# Stop the Perforce server import os import sys # Add the nearby "code" directory to the module loading path sys.path.insert(0, '.') import socket import string import imp import copy import re hostname = string.lower(string.split(socket.gethostname(), '.')[0]) config_filename = 'config_' + hostname + '.py' if not os.path.exists(config_filename): print "Could not find config file", config_filename config_file = open(config_filename) try: imp.load_source('config', config_filename, config_file) finally: config_file.close() original_configuration = copy.copy(sys.modules['config'].__dict__) import config from win32com.client import Dispatch, GetActiveObject import win32pdh, win32api, win32pdhutil, win32con class pyperf: def __init__(self): self.object='process' self.item='ID Process' def proclist(self, ): try: win32pdh.EnumObjects(None, None, 0, 1) junk, instances = win32pdh.EnumObjectItems(None, None, self.object, win32pdh.PERF_DETAIL_WIZARD) return instances except: raise "Problem getting process list" def procids(self): #each instance is a process, you can have multiple processes w/same name instances=self.proclist() proc_ids=[] proc_dict={} for instance in instances: if proc_dict.has_key(instance): proc_dict[instance] = proc_dict[instance] + 1 else: proc_dict[instance]=0 for instance, max_instances in proc_dict.items(): for inum in xrange(max_instances+1): try: hq = win32pdh.OpenQuery() # initializes the query handle path = win32pdh.MakeCounterPath( (None,self.object,instance, None, inum, self.item) ) counter_handle=win32pdh.AddCounter(hq, path) #convert counter path to counter handle win32pdh.CollectQueryData(hq) #collects data for the counter type, val = win32pdh.GetFormattedCounterValue(counter_handle, win32pdh.PDH_FMT_LONG) proc_ids.append(instance+'\t'+str(val)) win32pdh.CloseQuery(hq) except: raise "Problem getting process id" proc_ids.sort() return proc_ids def kill(self, procname): p4dre = re.compile(procname, re.IGNORECASE) plist = filter(p4dre.search, self.proclist()) if len(plist)>0: ## print "Found %s: %s" % (procname, plist[0]) pids = filter(p4dre.search, p.procids()) for pid in pids: ## print "Found %s: %s" % (procname, pids[0]) match = re.match(r".*\t(.*)$", pid) if match: pid = int(match.group(1)) print "Stopping process %s %d" % (plist[0], pid) handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0,pid) win32api.TerminateProcess(handle,0) win32api.CloseHandle(handle) return plist if __name__=='__main__': p = pyperf() procname = "^p4d-" plist = p.kill(procname) if len(plist)==0: print "Can't find process matching %s" % procname