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 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 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 __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 get_all_values(self): ret = {} # self will retrieve the list of all object names in the class (i.e. all the network interface # names in the class "network interface" win32pdh.CollectQueryData(self.hq) for inst, counter_handle in self.counterdict.iteritems(): try: t, val = win32pdh.GetFormattedCounterValue( counter_handle, self._precision) ret[inst] = val except Exception as e: # exception usually means self type needs two data points to calculate. Wait # a bit and try again time.sleep(DATA_POINT_INTERVAL) win32pdh.CollectQueryData(self.hq) # if we get exception self time, just return it up try: t, val = win32pdh.GetFormattedCounterValue( counter_handle, self._precision) ret[inst] = val except Exception as e: raise e return ret
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
def get_counters(counter_list): """ Get the values for the passes list of counters Args: counter_list (list): A list of counters to lookup Returns: dict: A dictionary of counters and their values """ if not isinstance(counter_list, list): raise CommandExecutionError("counter_list must be a list of tuples") try: # Start a Query instances query = win32pdh.OpenQuery() # Build the counters counters = build_counter_list(counter_list) # Add counters to the Query for counter in counters: counter.add_to_query(query) # https://docs.microsoft.com/en-us/windows/desktop/perfctrs/collecting-performance-data win32pdh.CollectQueryData(query) # The sleep here is required for counters that require more than 1 # reading time.sleep(1) win32pdh.CollectQueryData(query) ret = {} for counter in counters: try: ret.update({counter.path: counter.value()}) except pywintypes.error as exc: if exc.strerror == "No data to return.": # Some counters are not active and will throw an error if # there is no data to return continue else: raise except pywintypes.error as exc: if exc.strerror == "No data to return.": # Sometimess, win32pdh.CollectQueryData can err # so just ignore it return {} else: raise finally: win32pdh.CloseQuery(query) return ret
def getcpuload(): cpupath = win32pdh.MakeCounterPath( (None, 'Processor', '_Total', None, -1, '% Processor Time')) query = win32pdh.OpenQuery(None, 0) counter = win32pdh.AddCounter(query, cpupath, 0) win32pdh.CollectQueryData(query) time.sleep(0.1) win32pdh.CollectQueryData(query) status, value = win32pdh.GetFormattedCounterValue( counter, win32pdh.PDH_FMT_LONG) return float(value) / 100.0
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 get_counter_val(counter_path, *args, **kwargs): try: sleep = float(kwargs['sleep'][0]) except (KeyError, TypeError, IndexError): sleep = 0 try: factor = int(kwargs['factor'][0]) except (KeyError, TypeError, IndexError): factor = 0 # Allow using PDH_FMT_LONG for certain counter types if it is required fmt = win32pdh.PDH_FMT_DOUBLE try: fmt = int(kwargs['format'][0]) if fmt == 1: fmt = win32pdh.PDH_FMT_LONG except (KeyError, TypeError, IndexError): pass query = win32pdh.OpenQuery() try: counter = win32pdh.AddCounter(query, counter_path) try: if factor != 0: # Multiply results by 10^(factor) to get around limitations on threshold types win32pdh.SetCounterScaleFactor(counter, factor) win32pdh.CollectQueryData(query) if sleep != 0: time.sleep(sleep) win32pdh.CollectQueryData(query) _, _, _, _, _, _, _, info, _ = win32pdh.GetCounterInfo( counter, False) _, value = win32pdh.GetFormattedCounterValue(counter, fmt) 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 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 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 getcpuload(): """ Returns total CPU usage as fraction (0..1). Warning: side-effect: sleeps for 0.1 second to do diff """ # mempath = win32pdh.MakeCounterPath((None, "Memory", None, None, -1, "Available MBytes")) cpupath = win32pdh.MakeCounterPath((None, "Processor", "_Total", None, -1, "% Processor Time")) query = win32pdh.OpenQuery(None, 0) counter = win32pdh.AddCounter(query, cpupath, 0) win32pdh.CollectQueryData(query) # Collect must be called twice for CPU, see http://support.microsoft.com/kb/262938 time.sleep(0.1) win32pdh.CollectQueryData(query) status, value = win32pdh.GetFormattedCounterValue(counter, win32pdh.PDH_FMT_LONG) return float(value) / 100.0
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 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 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 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 _query_counters(self): # Refresh the list of performance objects, see: # https://docs.microsoft.com/en-us/windows/win32/api/pdh/nf-pdh-pdhenumobjectitemsa#remarks try: # https://docs.microsoft.com/en-us/windows/win32/api/pdh/nf-pdh-pdhenumobjectsa # https://mhammond.github.io/pywin32/win32pdh__EnumObjects_meth.html win32pdh.EnumObjects(None, self._connection.server, win32pdh.PERF_DETAIL_WIZARD, True) except pywintypes.error as error: message = 'Error refreshing performance objects: {}'.format( error.strerror) self.submit_health_check(self.CRITICAL, message=message) self.log.error(message) return # Avoid collection of performance objects that failed to refresh collection_queue = [] for perf_object in self.perf_objects: self.log.debug('Refreshing counters for performance object: %s', perf_object.name) try: perf_object.refresh() except ConfigurationError as e: # Counters are lazily configured and any errors should prevent check execution exception_class = type(e) message = str(e) self.check_initializations.append( lambda: raise_exception(exception_class, message)) return except Exception as e: self.log.error( 'Error refreshing counters for performance object `%s`: %s', perf_object.name, e) else: collection_queue.append(perf_object) try: # https://docs.microsoft.com/en-us/windows/win32/api/pdh/nf-pdh-pdhcollectquerydata # https://mhammond.github.io/pywin32/win32pdh__CollectQueryData_meth.html win32pdh.CollectQueryData(self._connection.query_handle) except pywintypes.error as error: message = 'Error querying performance counters: {}'.format( error.strerror) self.submit_health_check(self.CRITICAL, message=message) self.log.error(message) return for perf_object in collection_queue: self.log.debug('Collecting query data for performance object: %s', perf_object.name) try: perf_object.collect() except Exception as e: self.log.error( 'Error collecting query data for performance object `%s`: %s', perf_object.name, e) self.submit_health_check(self.OK)
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 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 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 getCounterValue(self, counter): # Update counter paths, to catch any new child processes that might # have been launched since last call. Then iterate through all # counter paths for this counter, and return a combined value. aggregateValue = 0 self.updateCounterPathsForChildProcesses(counter) hq = self.registeredCounters[counter][0] # This call can throw an exception in the case where all counter paths # are invalid (i.e., all the processes have terminated). try: win32pdh.CollectQueryData(hq) except: return None for singleCounter in self.registeredCounters[counter][1]: hc = singleCounter[0] try: type, val = win32pdh.GetFormattedCounterValue( hc, win32pdh.PDH_FMT_LONG) except: val = 0 aggregateValue += val return aggregateValue
def collectdataslave(self, format=win32pdh.PDH_FMT_LONG): ''' ### Not a public method Called only when the Query is known to be open, runs over the whole set of counters, appending results to the temp, returns the values as a list. ''' try: win32pdh.CollectQueryData(self._base) temp = [] for counter in self.counters: ok = 0 try: if counter: temp.append( win32pdh.GetFormattedCounterValue(counter, format)[1]) ok = 1 except win32api.error: pass if not ok: temp.append(-1) # a better way to signal failure??? return temp except win32api.error: # will happen if, for instance, no counters are part of the query and we attempt to collect data for it. return [-1] * len(self.counters)
def get_usage(self): win32pdh.CollectQueryData(self.base) try: value = win32pdh.GetFormattedCounterValue(self.counter, win32pdh.PDH_FMT_LONG)[1] except pywintypes.error: value = 0 return value
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 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 get(self, pause=None): """Return a dictionary of all counters added by addCounter(). If pause is set (positive integer) then wait this number of seconds between two consequetive queries. Some stats need two queries so the result can be averaged. """ win32pdh.CollectQueryData(self.hq) if pause: time.sleep(pause) win32pdh.CollectQueryData(self.hq) perfvals = {} for c in self.counters: val = c.getValue() perfvals[c.name] = val return perfvals
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