On 12/06/2007, at 8:01 AM, Michael Foord wrote: > I recently blogged about how listing all running processes is easy > with > IronPython [1]. > > This contrasts with the pywin32 solution we were using which is a > 'touch' more obscure (!) and has recently started failing on one > machine. However, I'm pretty certain that the pywin32 code we are > listing is 'sub-optimal'. > > Can anyone suggest a better solution?
If by better you mean clearer to read, then the wmi module (as Tim suggested) is probably the best. If by better you mean faster, I find that using the Process32First/Process32Next methods via ctypes the fastest. Here, it takes about 6 seconds to get a complete list with win32pdh, about 3 seconds with wmi, about 0.25 seconds with wmi- via-win32com, and about 0.015 seconds with ctypes. The only differences in the returned results are that win32pdh returns a "_Total" 'process', and calls idle "Idle", WMI (either way) calls idle "System Idle Process", and the ctypes method calls it "[System Process]". While the ctypes method is fast, it's not particularly clear, however :) import ctypes import win32con TH32CS_SNAPPROCESS = 0x00000002 class PROCESSENTRY32(ctypes.Structure): _fields_ = [("dwSize", ctypes.c_ulong), ("cntUsage", ctypes.c_ulong), ("th32ProcessID", ctypes.c_ulong), ("th32DefaultHeapID", ctypes.c_ulong), ("th32ModuleID", ctypes.c_ulong), ("cntThreads", ctypes.c_ulong), ("th32ParentProcessID", ctypes.c_ulong), ("pcPriClassBase", ctypes.c_ulong), ("dwFlags", ctypes.c_ulong), ("szExeFile", ctypes.c_char * 260)] def process_list(): # See http://msdn2.microsoft.com/en-us/library/ms686701.aspx CreateToolhelp32Snapshot = ctypes.windll.kernel32.\ CreateToolhelp32Snapshot Process32First = ctypes.windll.kernel32.Process32First Process32Next = ctypes.windll.kernel32.Process32Next CloseHandle = ctypes.windll.kernel32.CloseHandle hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) pe32 = PROCESSENTRY32() pe32.dwSize = ctypes.sizeof(PROCESSENTRY32) if Process32First(hProcessSnap, ctypes.byref(pe32)) == win32con.FALSE: print >> sys.stderr, "Failed getting first process." return while True: yield pe32.szExeFile if Process32Next(hProcessSnap, ctypes.byref(pe32)) == win32con.FALSE: break CloseHandle(hProcessSnap) Cheers, Tony _______________________________________________ Python-win32 mailing list Python-win32@python.org http://mail.python.org/mailman/listinfo/python-win32