how to find a process by name in Windows using Python

Here’s an interesting and useful tidbit.

There’s a part of slideboxx where I need to find out whether a particular process is running. I used the method in killProcName.py referenced in “Python Programming on Win32″ (assuming you installed win32all a.k.a. pywin32 a.k.a. Python for Windows extensions, the code can be found in $PYTHONHOME\Lib\site-packages\win32\scripts). The code I was using looks something like this: 

import win32pdhutil
win32pdhutil.GetPerformanceAttributes( 'Process', 'ID Process', 'process_name' )
processIDs = win32pdhutil.FindPerformanceAttributesByName( 'process_name' )

This worked fine on my test system; however, I received reports from users that the functionality that called this code was slow. As an aside, it’s almost always a challenge to go from the report of “it’s too slow when I click on this” to knowing what part of the code is causing the problem, especially when you can’t reproduce the issue!  After narrowing down the issue, I hit up google for help and came across a newsgroup message with a solution and ended up using the following code:

import win32pdh
def GetProcessID( name ) :
    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

With that change in place, users reported no more lag in that part of the program. I don’t understand Windows internals well enough to know why there is a difference.  What I do know is that it works and it improves the user experience.  If anyone can explain the difference, I’d appreciate it (and I’m sure others would too) if you left a comment with an explanation.  Thanks!

Advertisement

About this entry