def __init__(self): processor = win32pdhutil.find_pdh_counter_localized_name("Processor") processorTime = win32pdhutil.find_pdh_counter_localized_name("% Processor Time") path = win32pdh.MakeCounterPath((None,processor,"_Total", None, -1, processorTime)) self.base = win32pdh.OpenQuery() self.__counter = win32pdh.AddCounter(self.base, path) win32pdh.CollectQueryData(self.base) # the function addCounter change the locale to the current locale (french ?) # and implies problems of float to string conversion (.5 => "0,5") locale.setlocale(locale.LC_ALL, None) self.__processorLoad = 0 MEMORY = "Memory" COMMBYTES = "Available Bytes" memory = win32pdhutil.find_pdh_counter_localized_name(MEMORY) commbytes = win32pdhutil.find_pdh_counter_localized_name(COMMBYTES) path_comm = win32pdh.MakeCounterPath((None, memory, None, None, -1, commbytes)) self.base2 = win32pdh.OpenQuery() self.__counter2 = win32pdh.AddCounter(self.base2, path_comm) win32pdh.CollectQueryData(self.base2) # the function addCounter change the locale to the current locale (french ?) # and implies problems of float to string conversion (.5 => "0,5") locale.setlocale(locale.LC_ALL, None) self.__processorLoad = 0 self.__availableMemory = 0 locale.setlocale(locale.LC_ALL, "C")
def FindMyCounter(): pid_me = win32api.GetCurrentProcessId() object = "Process" items, instances = win32pdh.EnumObjectItems(None, None, object, -1) for instance in instances: # We use 2 counters - "ID Process" and "Working Set" counter = "ID Process" format = win32pdh.PDH_FMT_LONG hq = win32pdh.OpenQuery() path = win32pdh.MakeCounterPath( (None, object, instance, None, -1, "ID Process")) hc1 = win32pdh.AddCounter(hq, path) path = win32pdh.MakeCounterPath( (None, object, instance, None, -1, "Working Set")) hc2 = win32pdh.AddCounter(hq, path) win32pdh.CollectQueryData(hq) type, pid = win32pdh.GetFormattedCounterValue(hc1, format) if pid == pid_me: win32pdh.RemoveCounter(hc1) # not needed any more return hq, hc2 # Not mine - close the query and try again win32pdh.RemoveCounter(hc1) win32pdh.RemoveCounter(hc2) win32pdh.CloseQuery(hq) else: raise RuntimeError, "Can't find myself!?"
def __init__(self, ffprocess, process, counters=None, childProcess="plugin-container"): self.ffprocess = ffprocess self.childProcess = childProcess self.registeredCounters = {} self.registerCounters(counters) # PDH might need to be "refreshed" if it has been queried while the browser # is closed win32pdh.EnumObjects(None, None, 0, 1) # Add the counter path for the default process. for counter in self.registeredCounters: path = win32pdh.MakeCounterPath( (None, 'process', process, None, -1, counter)) hq = win32pdh.OpenQuery() try: hc = win32pdh.AddCounter(hq, path) except: win32pdh.CloseQuery(hq) #assume that this is a memory counter for the system, not a process counter path = win32pdh.MakeCounterPath( (None, 'Memory', None, None, -1, counter)) hq = win32pdh.OpenQuery() try: hc = win32pdh.AddCounter(hq, path) except: win32pdh.CloseQuery(hq) self.registeredCounters[counter] = [hq, [(hc, path)]] self.updateCounterPathsForChildProcesses(counter)
def __init__(self, class_name, counter_name, log, instance_name = None, machine_name = None, precision=None): self._get_counter_dictionary() self._class_name = win32pdh.LookupPerfNameByIndex(None, int(WinPDHCounter.pdh_counter_dict[class_name])) self._counter_name = win32pdh.LookupPerfNameByIndex(None, int(WinPDHCounter.pdh_counter_dict[counter_name])) self._is_single_instance = False self.hq = win32pdh.OpenQuery() self.logger = log self.counterdict = {} if precision is None: self._precision = win32pdh.PDH_FMT_DOUBLE else: self._precision = precision counters, instances = win32pdh.EnumObjectItems(None, machine_name, self._class_name, win32pdh.PERF_DETAIL_WIZARD) if instance_name is None and len(instances) > 0: for inst in instances: path = win32pdh.MakeCounterPath((machine_name, self._class_name, inst, None, 0, self._counter_name)) try: self.counterdict[inst] = win32pdh.AddCounter(self.hq, path) except: # noqa: E722 self.logger.fatal("Failed to create counter. No instances of %s\%s" % ( self._class_name, self._counter_name)) try: self.logger.debug("Path: %s\n" % unicode(path)) except: # noqa: E722 # some unicode characters are not translatable here. Don't fail just # because we couldn't log self.logger.debug("Failed to log path") pass else: if instance_name is not None: # check to see that it's valid if len(instances) <= 0: self.logger.error("%s doesn't seem to be a multi-instance counter, but asked for specific instance %s" % ( class_name, instance_name )) return if instance_name not in instances: self.logger.error("%s is not a counter instance in %s" % ( instance_name, class_name )) return path = win32pdh.MakeCounterPath((machine_name, self._class_name, instance_name, None, 0, self._counter_name)) try: self.logger.debug("Path: %s\n" % unicode(path)) except: # noqa: E722 # some unicode characters are not translatable here. Don't fail just # because we couldn't log self.logger.debug("Failed to log path") pass try: self.counterdict[SINGLE_INSTANCE_KEY] = win32pdh.AddCounter(self.hq, path) except: # noqa: E722 self.logger.fatal("Failed to create counter. No instances of %s\%s" % ( self._class_name, self._counter_name)) raise self._is_single_instance = True
def collect_counters(self): counters, instances = win32pdh.EnumObjectItems( None, self._machine_name, self.class_name, win32pdh.PERF_DETAIL_WIZARD ) if self._instance_name is None and len(instances) > 0: all_instances = set() for inst in instances: path = self._make_counter_path(self._machine_name, self._counter_name, inst, counters) if not path: continue all_instances.add(inst) try: if inst not in self.counterdict: self.logger.debug('Adding instance `%s`', inst) self.counterdict[inst] = win32pdh.AddCounter(self.hq, path) except: # noqa: E722, B001 self.logger.fatal( "Failed to create counter. No instances of %s\\%s" % (self.class_name, self._counter_name) ) expired_instances = set(self.counterdict) - all_instances for inst in expired_instances: self.logger.debug('Removing expired instance `%s`', inst) del self.counterdict[inst] else: if self._instance_name is not None: # check to see that it's valid if len(instances) <= 0: self.logger.error( "%s doesn't seem to be a multi-instance counter, but asked for specific instance %s", self.class_name, self._instance_name, ) raise AttributeError("%s is not a multi-instance counter" % self.class_name) if self._instance_name not in instances: self.logger.error("%s is not a counter instance in %s", self._instance_name, self.class_name) raise AttributeError("%s is not an instance of %s" % (self._instance_name, self.class_name)) path = self._make_counter_path(self._machine_name, self._counter_name, self._instance_name, counters) if not path: self.logger.warning("Empty path returned") elif win32pdh.ValidatePath(path) != 0: # Multi-instance counter with no instances presently pass else: try: if SINGLE_INSTANCE_KEY not in self.counterdict: self.logger.debug('Adding single instance for path `%s`', path) self.counterdict[SINGLE_INSTANCE_KEY] = win32pdh.AddCounter(self.hq, path) except: # noqa: E722, B001 self.logger.fatal( "Failed to create counter. No instances of %s\\%s" % (self.class_name, self._counter_name) ) raise self._is_single_instance = True
def __win32LogProfile(self, instance, inum, threads, interval, file): # create the process performance counters process_counters=[] process_query=win32pdh.OpenQuery() for counter in "Working Set", "Virtual Bytes", "Private Bytes", "Thread Count", "Handle Count": path = win32pdh.MakeCounterPath( (None, "Process", instance, None, inum, counter) ) process_counters.append(win32pdh.AddCounter(process_query, path)) win32pdh.CollectQueryData(process_query) # create the thread performance counter thread_counters=[] thread_query=win32pdh.OpenQuery() for (instance, inum) in threads: path=win32pdh.MakeCounterPath( (None, "Thread", instance, None, inum, "% Processor Time") ) thread_counters.append(win32pdh.AddCounter(thread_query, path)) win32pdh.CollectQueryData(thread_query) # perform the continual data collection until the thread is no longer active data = [0]*(len(process_counters)+1) try: while self.active: win32pdh.CollectQueryData(process_query) win32pdh.CollectQueryData(thread_query) for i in range(len(process_counters)): try: data[i+1] = win32pdh.GetFormattedCounterValue(process_counters[i], win32pdh.PDH_FMT_LONG)[1] except win32api.error: data[i+1] = -1 data[0]=0 for i in range(0, len(thread_counters)): try: data[0]=data[0]+win32pdh.GetFormattedCounterValue(thread_counters[i], win32pdh.PDH_FMT_LONG)[1] except Exception: pass currentTime = time.strftime("%d/%m/%y %H:%M:%S", time.gmtime(time.time())) file.write( "%s\t%s\t%d\t%d\t%d\t%d\t%d\n" % (currentTime, data[0]//self.numProcessors, float(data[1])/1024, float(data[2])/1024, float(data[3])/1024, float(data[4]), float(data[5]))) file.flush() time.sleep(interval) finally: # clean up for c in process_counters: win32pdh.RemoveCounter(c) win32pdh.CloseQuery(process_query) for c in thread_counters: win32pdh.RemoveCounter(c) win32pdh.CloseQuery(thread_query) if file != sys.stdout: file.close() self.active = 0
def getdiskio(self): if not self.diskioquery: self.diskioquery = win32pdh.OpenQuery() self.diskiohandles = ( win32pdh.AddCounter(self.diskioquery, r'\PhysicalDisk(_Total)\Disk Read Bytes/sec'), win32pdh.AddCounter(self.diskioquery, r'\PhysicalDisk(_Total)\Disk Write Bytes/sec') ) win32pdh.CollectQueryData(self.diskioquery) win32pdh.CollectQueryData(self.diskioquery) discard, r = win32pdh.GetFormattedCounterValue(self.diskiohandles[0], win32pdh.PDH_FMT_LONG) discard, w = win32pdh.GetFormattedCounterValue(self.diskiohandles[1], win32pdh.PDH_FMT_LONG) return r+w
def main(argv): scheduler = BlockingScheduler() global hq hq = win32pdh.OpenQuery() counters, instances = win32pdh.EnumObjectItems(None, None, 'Process', win32pdh.PERF_DETAIL_WIZARD) proc_num = {} for instance in instances: if instance == '_Total' or instance == 'Idle' or instance == 'System': continue if instance in proc_num: proc_num[instance] = proc_num[instance] + 1 else: proc_num[instance] = 1 for instance in proc_num: num = proc_num[instance] for id in xrange(num): instance_with_id = '%s#%d' % (instance, id) counter_dict[instance_with_id] = {} path = win32pdh.MakeCounterPath((None, 'Process', instance, None, id, 'ID Process')) counter_dict[instance_with_id]['proc_id'] = win32pdh.AddCounter(hq, path) path = win32pdh.MakeCounterPath((None, 'Process', instance, None, id, '% Processor Time')) counter_dict[instance_with_id]['cpu_usert'] = win32pdh.AddCounter(hq, path) path = win32pdh.MakeCounterPath((None, 'Process', instance, None, id, 'Elapsed Time')) counter_dict[instance_with_id]['cpu_tm_ss'] = win32pdh.AddCounter(hq, path) path = win32pdh.MakeCounterPath((None, 'Process', instance, None, id, 'Page Faults/sec')) counter_dict[instance_with_id]['pf'] = win32pdh.AddCounter(hq, path) path = win32pdh.MakeCounterPath((None, 'Process', instance, None, id, 'Priority Base')) counter_dict[instance_with_id]['prit_rnk'] = win32pdh.AddCounter(hq, path) path = win32pdh.MakeCounterPath((None, 'Process', instance, None, id, 'Thread Count')) counter_dict[instance_with_id]['thd_cnt'] = win32pdh.AddCounter(hq, path) path = win32pdh.MakeCounterPath((None, 'Process', instance, None, id, 'Private Bytes')) counter_dict[instance_with_id]['vir_mem_byt_cnt'] = win32pdh.AddCounter(hq, path) path = win32pdh.MakeCounterPath((None, 'Process', instance, None, id, 'Creating Process ID')) counter_dict[instance_with_id]['parent_pid'] = win32pdh.AddCounter(hq, path) path = win32pdh.MakeCounterPath((None, 'Process', instance, None, id, 'Handle Count')) counter_dict[instance_with_id]['svc_tm'] = win32pdh.AddCounter(hq, path) scheduler.add_job(query, 'cron', minute='*/1', second='0') scheduler.start() win32pdh.CloseQuery(hq)
def __init__(self, class_name, instance_name, log): self._get_counter_dictionary() self._class_name = win32pdh.LookupPerfNameByIndex( None, int(WinPDHCounter.pdh_counter_dict[class_name])) self._instance_name = win32pdh.LookupPerfNameByIndex( None, int(WinPDHCounter.pdh_counter_dict[instance_name])) self._is_single_instance = False self.hq = win32pdh.OpenQuery() self.logger = log self.counterdict = {} counters, instances = win32pdh.EnumObjectItems( None, None, self._class_name, win32pdh.PERF_DETAIL_WIZARD) if len(instances) > 0: for inst in instances: path = win32pdh.MakeCounterPath((None, self._class_name, inst, None, 0, self._instance_name)) try: self.counterdict[inst] = win32pdh.AddCounter(self.hq, path) except: self.logger.fatal( "Failed to create counter. No instances of %s\%s" % (self._class_name, self._instance_name)) try: self.logger.debug("Path: %s\n" % unicode(path)) except: # some unicode characters are not translatable here. Don't fail just # because we couldn't log self.logger.debug("Failed to log path") pass else: path = win32pdh.MakeCounterPath( (None, self._class_name, None, None, 0, self._instance_name)) try: self.logger.debug("Path: %s\n" % unicode(path)) except: # some unicode characters are not translatable here. Don't fail just # because we couldn't log self.logger.debug("Failed to log path") pass try: self.counterdict[SINGLE_INSTANCE_KEY] = win32pdh.AddCounter( self.hq, path) except: self.logger.fatal( "Failed to create counter. No instances of %s\%s" % (self._class_name, self._instance_name)) raise self._is_single_instance = True
def FindChildrenOf(self, parentid): childPids = [] object = "Process" items, instances = win32pdh.EnumObjectItems( None, None, object, win32pdh.PERF_DETAIL_WIZARD) instance_dict = {} for instance in instances: if instance in instance_dict: instance_dict[instance] += 1 else: instance_dict[instance] = 0 for instance, max_instances in instance_dict.items(): for inum in range(max_instances + 1): hq = win32pdh.OpenQuery() try: hcs = [] path = win32pdh.MakeCounterPath( (None, object, instance, None, inum, "ID Process")) hcs.append(win32pdh.AddCounter(hq, path)) path = win32pdh.MakeCounterPath( (None, object, instance, None, inum, "Creating Process ID")) hcs.append(win32pdh.AddCounter(hq, path)) try: # If the process goes away unexpectedly this call will fail win32pdh.CollectQueryData(hq) type, pid = win32pdh.GetFormattedCounterValue( hcs[0], win32pdh.PDH_FMT_LONG) type, ppid = win32pdh.GetFormattedCounterValue( hcs[1], win32pdh.PDH_FMT_LONG) if int(ppid) == parentid: childPids.append(int(pid)) except: pass finally: win32pdh.CloseQuery(hq) return childPids
def open(self): ''' Build the base query object for this wrapper, then add all of the counters required for the query. Raise a QueryError if we can't complete the functions. If we are already open, then do nothing. ''' if not self.active: # to prevent having multiple open queries # curpaths are made accessible here because of the possibility of volatile paths # which may be dynamically altered by subclasses. self.curpaths = copy.copy(self.paths) try: base = win32pdh.OpenQuery() for path in self.paths: try: self.counters.append(win32pdh.AddCounter(base, path)) except win32api.error: # we passed a bad path self.counters.append(0) pass self._base = base self.active = 1 return 0 # open succeeded except: # if we encounter any errors, kill the Query try: self.killbase(base) except NameError: # failed in creating query pass self.active = 0 self.curpaths = [] raise QueryError(self) return 1 # already open
def GetProcesses(): win32pdh.EnumObjects(None, None, win32pdh.PERF_DETAIL_WIZARD) junk, instances = win32pdh.EnumObjectItems(None,None,'Process', win32pdh.PERF_DETAIL_WIZARD ) proc_dict = {} for instance in instances: if proc_dict.has_key(instance): proc_dict[instance] = proc_dict[instance] + 1 else: proc_dict[instance]=0 proc_ids = [] for instance, max_instances in proc_dict.items(): for inum in xrange(max_instances+1): hq = win32pdh.OpenQuery() # initializes the query handle try: path = win32pdh.MakeCounterPath( (None, 'Process', instance, None, inum, 'ID Process') ) counter_handle=win32pdh.AddCounter(hq, path) #convert counter path to counter handle try: win32pdh.CollectQueryData(hq) #collects data for the counter type, val = win32pdh.GetFormattedCounterValue(counter_handle, win32pdh.PDH_FMT_LONG) proc_ids.append((instance, val)) except win32pdh.error, e: print e win32pdh.RemoveCounter(counter_handle) except win32pdh.error, e: print e win32pdh.CloseQuery (hq)
def isProcessRunning(pid): if sys.platform == "win32": # First get a list of all processes. All we get is the process name ignoreme, processNames = win32pdh.EnumObjectItems( None, None, 'process', win32pdh.PERF_DETAIL_WIZARD) processCounts = {} for name in processNames: if name in processCounts: processCounts[name] = processCounts[name] + 1 else: processCounts[name] = 0 # For each process, get the pid. Stop if we find our PID found = False for name, nprocs in processCounts.items(): if found: break for procNum in xrange(0, nprocs + 1): hq = win32pdh.OpenQuery() path = win32pdh.MakeCounterPath( (None, 'process', name, None, procNum, 'ID Process')) counter_handle = win32pdh.AddCounter(hq, path) win32pdh.CollectQueryData(hq) type, val = win32pdh.GetFormattedCounterValue( counter_handle, win32pdh.PDH_FMT_LONG) win32pdh.CloseQuery(hq) if val == pid: found = True break return found else: # unix psoutput = runCommandCaptureOutput("ps -p %s" % pid, True) return len(psoutput) >= 2
def count_processes(): object = 'Process' items, instances = win32pdh.EnumObjectItems(None, None, object, win32pdh.PERF_DETAIL_WIZARD) instance_dict = {} for instance in instances: try: instance_dict[instance] = instance_dict[instance] + 1 except KeyError: instance_dict[instance] = 0 counters = {} hcs = [] hq = win32pdh.OpenQuery() for instance, max_instances in instance_dict.items(): for inum in range(max_instances + 1): if instance == 'chrome': path = win32pdh.MakeCounterPath((None, object, instance, None, inum, 'Creating Process ID')) hcs.append(win32pdh.AddCounter(hq, path)) win32pdh.CollectQueryData(hq) for hc in hcs: try: type, val = win32pdh.GetFormattedCounterValue( hc, win32pdh.PDH_FMT_LONG) except win32pdh.counter_status_error: pass try: counters[val] += 1 except KeyError: counters[val] = 1 win32pdh.RemoveCounter(hc) win32pdh.CloseQuery(hq) return counters
def get_counter_val(counter_path, *args, **kwargs): try: sleep = float(kwargs['sleep'][0]) except (KeyError, TypeError, IndexError): sleep = 0 query = win32pdh.OpenQuery() try: counter = win32pdh.AddCounter(query, counter_path) try: win32pdh.CollectQueryData(query) if sleep != 0: time.sleep(sleep) win32pdh.CollectQueryData(query) _, _, _, _, _, _, _, info, _ = win32pdh.GetCounterInfo(counter, False) _, value = win32pdh.GetFormattedCounterValue(counter, win32pdh.PDH_FMT_DOUBLE) finally: win32pdh.RemoveCounter(counter) finally: win32pdh.CloseQuery(query) unit = info[-1] if not isinstance(value, (int, long)): value = round(value, 2) return [value, unit]
def GetPerformanceAttributes(object, counter, instance=None, inum=-1, format=None, machine=None): # NOTE: Many counters require 2 samples to give accurate results, # including "% Processor Time" (as by definition, at any instant, a # thread's CPU usage is either 0 or 100). To read counters like this, # you should copy this function, but keep the counter open, and call # CollectQueryData() each time you need to know. # See http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp # My older explanation for this was that the "AddCounter" process forced # the CPU to 100%, but the above makes more sense :) import win32pdh if format is None: format = win32pdh.PDH_FMT_LONG path = win32pdh.MakeCounterPath( (machine, object, instance, None, inum, counter)) hq = win32pdh.OpenQuery() try: hc = win32pdh.AddCounter(hq, path) try: win32pdh.CollectQueryData(hq) type, val = win32pdh.GetFormattedCounterValue(hc, format) return val finally: win32pdh.RemoveCounter(hc) finally: win32pdh.CloseQuery(hq)
def procids(): #each instance is a process, you can have multiple processes w/same name junk, instances = win32pdh.EnumObjectItems(None, None, 'process', win32pdh.PERF_DETAIL_WIZARD) proc_ids = [] proc_dict = {} for instance in instances: if instance in proc_dict: 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): hq = win32pdh.OpenQuery() # initializes the query handle path = win32pdh.MakeCounterPath( (None, 'process', instance, None, inum, 'ID Process')) counter_handle = win32pdh.AddCounter(hq, path) win32pdh.CollectQueryData(hq) #collects data for the counter type, val = win32pdh.GetFormattedCounterValue( counter_handle, win32pdh.PDH_FMT_LONG) proc_ids.append((instance, str(val))) win32pdh.CloseQuery(hq) proc_ids.sort() return proc_ids
def mem_used(): counter = r'\Memory\Committed Bytes' machine, object, instance, parentInstance, index, counter = win32pdh.ParseCounterPath( counter) instance = None inum = -1 format = win32pdh.PDH_FMT_DOUBLE machine = None path = win32pdh.MakeCounterPath( (machine, object, instance, None, inum, counter)) hq = win32pdh.OpenQuery() try: hc = win32pdh.AddCounter(hq, path) try: win32pdh.CollectQueryData(hq) type, val = win32pdh.GetFormattedCounterValue(hc, format) return int(val / 1024) except pywintypes.error: return 0 finally: win32pdh.RemoveCounter(hc) finally: win32pdh.CloseQuery(hq)
def querysinglecounter(self, path, fmt): h = win32pdh.OpenQuery() c = win32pdh.AddCounter(h, path) win32pdh.CollectQueryData(h) discard, v = win32pdh.GetFormattedCounterValue(c, fmt) win32pdh.CloseQuery(h) return v
def process_list_nt(): # each instance is a process, you can have multiple processes w/same name processLocalizedName = win32pdhutil.find_pdh_counter_localized_name( "Process") junk, instances = win32pdh.EnumObjectItems(None, None, processLocalizedName, win32pdh.PERF_DETAIL_WIZARD) proc_ids = {} proc_dict = {} for instance in instances: if instance in proc_dict: proc_dict[instance] = proc_dict[instance] + 1 else: proc_dict[instance] = 0 idProcessLocalizedName = win32pdhutil.find_pdh_counter_localized_name( "ID Process") for instance, max_instances in list(proc_dict.items()): for inum in range(max_instances + 1): hq = win32pdh.OpenQuery() # initializes the query handle path = win32pdh.MakeCounterPath( (None, processLocalizedName, instance, None, inum, idProcessLocalizedName)) counter_handle = win32pdh.AddCounter(hq, path) win32pdh.CollectQueryData(hq) # collects data for the counter type, val = win32pdh.GetFormattedCounterValue( counter_handle, win32pdh.PDH_FMT_LONG) proc_ids[str(val)] = instance win32pdh.CloseQuery(hq) return proc_ids
def fget(self): import win32pdh object = 'Process' items, instances = win32pdh.EnumObjectItems(None, None, object, win32pdh.PERF_DETAIL_WIZARD) instance_dict = {} for instance in instances: try: instance_dict[instance] = instance_dict[instance] + 1 except KeyError: instance_dict[instance] = 0 procs = [] for instance, max_instances in instance_dict.items(): t = [] for inum in xrange(max_instances+1): hq = win32pdh.OpenQuery() hcs = [] for item in ['ID Process', 'Creating Process ID']: path = win32pdh.MakeCounterPath((None,object,instance,None,inum,item)) hcs.append(win32pdh.AddCounter(hq,path)) win32pdh.CollectQueryData(hq) t.append(instance) for hc in hcs: type,val=win32pdh.GetFormattedCounterValue(hc,win32pdh.PDH_FMT_LONG) t.append(val) win32pdh.RemoveCounter(hc) win32pdh.CloseQuery(hq) procs.append(t) return procs
def updateCounterPathsForChildProcesses(self, counter): # Create a counter path for each instance of the child process that # is running. If any of these paths are not in our counter list, # add them to our counter query and append them to the counter list, # so that we'll begin tracking their statistics. We don't need to # worry about removing invalid paths from the list, as getCounterValue() # will generate a value of 0 for those. hq = self.registeredCounters[counter][0] win32pdh.EnumObjects(None, None, 0, 1) counterListLength = len(self.registeredCounters[counter][1]) try: expandedCounterPaths = \ win32pdh.ExpandCounterPath('\\process(%s*)\\%s' % (self.childProcess, counter)) except: return for expandedPath in expandedCounterPaths: alreadyInCounterList = False for singleCounter in self.registeredCounters[counter][1]: if expandedPath == singleCounter[1]: alreadyInCounterList = True if not alreadyInCounterList: try: counterHandle = win32pdh.AddCounter(hq, expandedPath) self.registeredCounters[counter][1].append( (counterHandle, expandedPath)) except: continue if counterListLength != len(self.registeredCounters[counter][1]): try: win32pdh.CollectQueryData(hq) except: return
def GetProcessID ( name ) : if os.name != 'nt' : return None else: import win32pdh import time object = "Process" items, instances = win32pdh.EnumObjectItems(None,None,object, win32pdh.PERF_DETAIL_WIZARD) val = None if name in instances : hq = win32pdh.OpenQuery() hcs = [] item = "ID Process" path = win32pdh.MakeCounterPath( (None,object,name, None, 0, item) ) hcs.append(win32pdh.AddCounter(hq, path)) win32pdh.CollectQueryData(hq) time.sleep(0.01) win32pdh.CollectQueryData(hq) for hc in hcs: type, val = win32pdh.GetFormattedCounterValue(hc, win32pdh.PDH_FMT_LONG) win32pdh.RemoveCounter(hc) win32pdh.CloseQuery(hq) return val
def ShowAllProcesses(): object = find_pdh_counter_localized_name("Process") items, instances = win32pdh.EnumObjectItems(None, None, object, win32pdh.PERF_DETAIL_WIZARD) # Need to track multiple instances of the same name. instance_dict = {} for instance in instances: try: instance_dict[instance] = instance_dict[instance] + 1 except KeyError: instance_dict[instance] = 0 # Bit of a hack to get useful info. items = [find_pdh_counter_localized_name("ID Process")] + items[:5] print("Process Name", ",".join(items)) for instance, max_instances in instance_dict.items(): for inum in range(max_instances + 1): hq = win32pdh.OpenQuery() hcs = [] for item in items: path = win32pdh.MakeCounterPath((None, object, instance, None, inum, item)) hcs.append(win32pdh.AddCounter(hq, path)) win32pdh.CollectQueryData(hq) # as per http://support.microsoft.com/default.aspx?scid=kb;EN-US;q262938, some "%" based # counters need two collections time.sleep(0.01) win32pdh.CollectQueryData(hq) print("%-15s\t" % (instance[:15]), end=' ') for hc in hcs: type, val = win32pdh.GetFormattedCounterValue(hc, win32pdh.PDH_FMT_LONG) print("%5d" % (val), end=' ') win32pdh.RemoveCounter(hc) print() win32pdh.CloseQuery(hq)
def getProcessPrefix(self, pid): object = "Process" items, instances = win32pdh.EnumObjectItems( None, None, object, win32pdh.PERF_DETAIL_WIZARD) # Need to track multiple instances of the same name. instance_dict = {} for instance in instances: try: instance_dict[instance] = instance_dict[instance] + 1 except KeyError: instance_dict[instance] = 0 # Bit of a hack to get useful info. item = "ID Process" for instance, max_instances in instance_dict.items(): for inum in xrange(max_instances + 1): hq = win32pdh.OpenQuery() try: hcs = [] path = win32pdh.MakeCounterPath( (None, object, instance, None, inum, item)) hc = win32pdh.AddCounter(hq, path) try: win32pdh.CollectQueryData(hq) type, val = win32pdh.GetFormattedCounterValue( hc, win32pdh.PDH_FMT_LONG) if val == pid: return "\\".join(path.split("\\")[:-1]) + "\\" finally: win32pdh.RemoveCounter(hc) finally: win32pdh.CloseQuery(hq)
def main(argv): scheduler = BlockingScheduler() global hq hq = win32pdh.OpenQuery() global chs chs = { 'pgin': win32pdh.AddCounter(hq, "\\Memory\\Pages Input/sec"), 'pgout': win32pdh.AddCounter(hq, "\\Memory\\Pages Output/sec"), 'pgfault': win32pdh.AddCounter(hq, "\\Memory\\Page Faults/sec") } scheduler.add_job(query, 'cron', minute='*/1', second='0') scheduler.start() win32pdh.CloseQuery(hq)
def open(self, hq): """Open a counter request from an already open win32pdh query. """ self.path = win32pdh.MakeCounterPath( (self.machine, self.object, self.instance, None, self.inum, self.counter)) self.hc = win32pdh.AddCounter(hq, self.path)
def add_to_query(self, query): ''' Add the current path to the query Args: query (obj): The handle to the query to add the counter ''' self.handle = win32pdh.AddCounter(query, self.path)
def getnetwork(self, netquery=None): # FIXME: takes first nic instead of total if not self.netquery: self.netquery = win32pdh.OpenQuery() iface = win32pdh.EnumObjectItems(None, None, 'Network Interface', win32pdh.PERF_DETAIL_WIZARD, 0)[1][0] rxpath = win32pdh.MakeCounterPath( (None, 'Network Interface', iface, None, 0, 'Bytes Received/sec') ) txpath = win32pdh.MakeCounterPath( (None, 'Network Interface', iface, None, 0, 'Bytes Sent/sec') ) self.nethandles = ( win32pdh.AddCounter(self.netquery, rxpath), win32pdh.AddCounter(self.netquery, txpath) ) win32pdh.CollectQueryData(self.netquery) win32pdh.CollectQueryData(self.netquery) discard, rx = win32pdh.GetFormattedCounterValue(self.nethandles[0], win32pdh.PDH_FMT_LONG) discard, tx = win32pdh.GetFormattedCounterValue(self.nethandles[1], win32pdh.PDH_FMT_LONG) return rx, tx
def getcpu(self): if not self.cpuquery: self.cpuquery = win32pdh.OpenQuery() self.cpuhandle = win32pdh.AddCounter(self.cpuquery, r'\Processor(_Total)\% Idle Time') win32pdh.CollectQueryData(self.cpuquery) win32pdh.CollectQueryData(self.cpuquery) discard, val = win32pdh.GetFormattedCounterValue(self.cpuhandle, win32pdh.PDH_FMT_DOUBLE) return 100.0 - val