Welcome, guest | Sign In | My Account | Store | Cart
1

To get process information for both NT and W2K (but not the 9x family) you can use the Performance Data Helper library(PDH). The is a simple example that shows you how to get a process list and their ids. It provides a convenient interface to performance information stored fundamentally in the registry. The basic process of using the PDH encompasses the following:

  1. Get a list of all the objects you want
  2. Get a list of the object's instances and data available for each instance: called 'items' or 'counters'
  3. Get a group of performance data for each counter

In the case here we want the process object, the object's instances are it's list of processes, and the counter we want for the processes is 'ID Process'.

Python, 27 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import win32pdh, string, win32api

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


print procids()

A whole sequence of calls are necessary to get process information. 1. PdhOpenQuery -- initialize query handle which contains ID Process counter 2. PdhMakeCounterPath -- make path for counter 3. PdhAddCounter -- group the counters paths together for the query 4. PdhCollectQueryData -- gathers the actual data 5. PdhGetFormattedCounterValue -- convert data to typical format 6. PdhCloseQuery -- close the counters and the query handle

Compared to similar C++ code to do the same thing, the python code is very clean. You can learn about more details about Performance Data Helper library by consulting http://msdn.microsoft.com.

2 comments

Eric Koome 12 years, 9 months ago  # | flag

I had done a similar recipe but using PSAPI.DLL and ctypes: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305279 Eric

Matt Doar 11 years, 11 months ago  # | flag

Sweet and relatively simple. This just worked. Thanks!

~Matt

Add a comment

Sign in to comment