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 __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 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 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 killbase(self, base=None): ''' ### This is not a public method Mission critical function to kill the win32pdh objects held by this object. User's should generally use the close method instead of this method, in case a sub-class has overridden close to provide some special functionality. ''' # Kill Pythonic references to the objects in this object's namespace self._base = None counters = self.counters self.counters = [] # we don't kill the curpaths for convenience, this allows the # user to close a query and still access the last paths self.active = 0 # Now call the delete functions on all of the objects try: map(win32pdh.RemoveCounter, counters) except: pass try: win32pdh.CloseQuery(base) except: pass del (counters) del (base)
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 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 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 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 disconnect(self): # https://docs.microsoft.com/en-us/windows/win32/api/pdh/nf-pdh-pdhclosequery # https://mhammond.github.io/pywin32/win32pdh__CloseQuery_meth.html win32pdh.CloseQuery(self.__query_handle) if self.network_resource is not None: self.network_resources.remove(self.network_resource)
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 _StopDebugger(self): try: if self.cpu_hq != None: win32pdh.RemoveCounter(self.cpu_counter_handle) win32pdh.CloseQuery(self.cpu_hq) self.cpu_hq = None self.cpu_counter_handle = None except: pass if self.thread != None and self.thread.is_alive(): self.quit.set() self.started.clear() self.thread.join(5) if self.thread.is_alive(): self.thread.terminate() self.thread.join() time.sleep(0.25) # Take a breath elif self.thread != None: # quit could be set by event handler now self.thread.join() self.thread = None
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 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 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 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 stopMonitor(self): try: for counter in self.registeredCounters: for singleCounter in self.registeredCounters[counter][1]: win32pdh.RemoveCounter(singleCounter[0]) win32pdh.CloseQuery(self.registeredCounters[counter][0]) self.registeredCounters.clear() except: print 'failed to stopMonitor'
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 get_processes_dict(self): """ returns a dictionary that contains all the processes PIDs as keys and names as values. :return: processes dictionary as described above. """ try: # Getting all processes name z, proc_name = win32pdh.EnumObjectItems(None, None, self.process_obj, win32pdh.PERF_DETAIL_WIZARD)# PERF_DETAIL_WIZARD = 400 instances = {} for instance in proc_name: if instance in instances: instances[instance] += 1 else: instances[instance] = 1 proc_pid_name = {} for instance, max_instances in instances.items(): for inum in xrange(max_instances + 1): try: hq = win32pdh.OpenQuery() # initializes the query handle path = win32pdh.MakeCounterPath((None, self.process_obj, 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_pid_name[val] = [instance] win32pdh.CloseQuery(hq) except: raise OSError("Problem getting process id") return proc_pid_name except: try: from win32com.client import GetObject WMI = GetObject('winmgmts:') # COM object proc_instances = WMI.InstancesOf('Win32_Process') # WMI instanse proc_name = [process.Properties_('Name').Value for process in proc_instances] # Get the processess names proc_id = [process.Properties_('ProcessId').Value for process in proc_instances] # Get the processess names proc_pid_name = {} proc_id_counter = 0 for instance in range(len(proc_name)): proc_pid_name[proc_id[instance]] = [(proc_name[instance])] proc_id_counter += 1 return proc_pid_name except: raise OSError('Counldnt get the process list')
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 close(self): if self.hc: try: win32pdh.RemoveCounter(self.hc) except: pass self.hc = None if self.hq: try: win32pdh.CloseQuery(self.hq) except: pass self.hq = None
def CleanupCounter(hq, hc): """Cleans up a counter after it is no longer needed. Args: hq: handle to the query for the counter hc: handle to the counter """ try: win32pdh.RemoveCounter(hc) win32pdh.CloseQuery(hq) except: # Sometimes we get unexpected win32 errors. Not much can be done. pass
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 startMonitor(self): # PDH might need to be "refreshed" if it has been queried while Firefox # is closed win32pdh.EnumObjects(None, None, 0, 1) for counter in self.registeredCounters: path = win32pdh.MakeCounterPath( (None, 'process', self.process, None, -1, counter)) hq = win32pdh.OpenQuery() try: hc = win32pdh.AddCounter(hq, path) except: win32pdh.CloseQuery(hq) self.registeredCounters[counter] = [hq, hc]
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 AddCounter(counter_name): """Adds a pdh query and counter of the given name to Firefox. Args: counter_name: The name of the counter to add, i.e. "% Processor Time" Returns: (query handle, counter handle) """ path = win32pdh.MakeCounterPath( (None, 'process', 'firefox', None, -1, counter_name)) hq = win32pdh.OpenQuery() try: hc = win32pdh.AddCounter(hq, path) except: win32pdh.CloseQuery(hq) return hq, hc
def close(self): for hc in self.hcs: if not hc: continue try: win32pdh.RemoveCounter(hc) except: pass self.hcs = [] for hq in self.hqs: if not hq: continue try: win32pdh.CloseQuery(hq) except: pass self.hqs = []