Kelie wrote: > hello, > > is there an easier way to get the name of current process? i'm using > wmi module from Tim Golden. here is what i have: > > def find_first_match(func, lst): > """Find 1st item in a list that yield True for a give function.""" > match = None > for i, elem in enumerate(lst): > if func(elem): > match = [i, elem] > break > return match > > def get_current_process_name(): > import wmi > import win32process > procList = wmi.WMI().Win32_Process() > hwnd = win32process.GetCurrentProcessId() > find = find_first_match(lambda p: int(p.Handle) == hwnd, procList) > if find: > return find[1].Name > else: > return None > > if __name__ == "__main__": > print get_current_process_name() > > the above code works. but it is slow. it always takes a few seconds to > get the procList. is it normal? > > thanks for your help >
I'm quite sure other people can come up with non-WMI solutions, but just a few pointers on what you have there: If you know what you're looking for (in this case: Win32_Process), you can avoid a certain overhead in startup by passing find_classes=False to the WMI function: <code> import wmi c = wmi.WMI (find_classes=False) </code> Then, you can let WMI do the heavy loading of finding a particular process: <code> import win32process import wmi c = wmi.WMI (find_classes=False) current_id = win32process.GetCurrentProcessId () for process in c.Win32_Process (Handle=current_id): break print process.Name </code> Finally, if you know you only need the name, you can specify the list of fields to return: <code> import win32process import wmi c = wmi.WMI (find_classes=False) current_id = win32process.GetCurrentProcessId () for process in c.Win32_Process (['Name'], Handle=current_id): break print process.Name </code> It's still not blindingly fast, but timeit gives... python -m timeit "import win32process; import wmi; print wmi.WMI (find_classes=0).Win32_Process (['Name'], Handle=win32proce ss.GetCurrentProcessId ())[0].Name" 10 loops, best of 3: 67.9 msec per loop ... which might or might not be adequate. Depends on what you need, and whether this is a one-shot tool or part of some larger setup where this small startup cost will be negligible. TJG _______________________________________________ Python-win32 mailing list Python-win32@python.org http://mail.python.org/mailman/listinfo/python-win32