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

This function will return a list of tuples of process names and ids. It should provide a starting point for grabbing other process related information out of the pdh.

Python, 35 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
28
29
30
31
32
33
34
35
import win32pdh
def get_processes():
    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
                    pass

                win32pdh.RemoveCounter(counter_handle)

            except win32pdh.error, e:
                #print e
                pass
            win32pdh.CloseQuery(hq) 

    return proc_ids

This function started from code taken from an article in the win32all documentation ("Getting process info: Win32 and COM with python and C++" by John Nielsen). Some gaps are filled in and it has taken a slight deviation from where the article was headed.

1 comment

Ukach Abraham 9 years, 9 months ago  # | flag

How can a you create a GUI for this script, with options to terminate the process, elevate the process and exit.