[python-win32] Finding and Exiting a Process

Cedric Delfosse cedric.delfosse at linbox.com
Mon Sep 20 11:15:17 CEST 2004


Le lun 20/09/2004 à 09:03, Lewis Franklin a écrit :
> [...]
> My question is if there is any way to find the process ID of the new
> program, either by capturing it when it is spawned or by somehow
> identifying the process (I do know the program name of the spawned
> program if that somehow helps).

To get all the pids of processes with a given name, I use this code:

def get_pid(name):
    # Flush process info internal cache
    win32pdh.EnumObjects(None, None, 0, 1)

    object = win32pdhutil.find_pdh_counter_localized_name("Process")
    try:
        items, instances = win32pdh.EnumObjectItems(None, None, object, win32pdh.PERF_DETAIL_WIZARD)
    except win32api.error:
        print "Error"
        return []

    # 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

    items = [win32pdhutil.find_pdh_counter_localized_name("ID Process")]

    result = []
    for instance, max_instances in instance_dict.items():
        for inum in xrange(max_instances+1):
            hq = win32pdh.OpenQuery()
            hcs = []
            path = win32pdh.MakeCounterPath( (None,object,instance, None, inum, win32pdhutil.find_pdh_counter_localized_name('ID Process')) )            hcs.append(win32pdh.AddCounter(hq, path))
            try:
                try:
                    win32pdh.CollectQueryData(hq)
                    for hc in hcs:
                        try:
                            type, val = win32pdh.GetFormattedCounterValue(hc, win32pdh.PDH_FMT_LONG)
                            if instance == name: result.append(val)
                        finally:
                            win32pdh.RemoveCounter(hc)
                finally:
                    win32pdh.CloseQuery(hq)
            except win32api.error:
                # Sometimes some calls fails on NT, I don't know why ...
                pass

    return result


Regards,

-- 
Cédric Delfosse                             Linbox / Free&ALter Soft
152, rue de Grigy - Technopole Metz              57070 Metz - FRANCE
tél: +33 (0)3 87 50 87 90                          http://linbox.com



More information about the Python-win32 mailing list