用python获得正在的运行的windows进程的有几种方式:
方式一
通过 PyWin32包对Windows进行处理。
可以通过这个获取系统信息,但仅限于windows系统。
import win32com.client wmi=win32com.client.GetObject('winmgmts:')for p in wmi.InstancesOf('win32_process'): print p.Name, p.Properties_('ProcessId'), \ int(p.Properties_('UserModeTime').Value)+int(p.Properties_('KernelModeTime').Value) children=wmi.ExecQuery('Select * from win32_process where ParentProcessId=%s' %p.Properties_('ProcessId')) for child in children: print '\t',child.Name,child.Properties_('ProcessId'), \ int(child.Properties_('UserModeTime').Value)+int(child.Properties_('KernelModeTime').Value)
运行结果:
System Idle Process 0 11055150937500 System Idle Process 0 11055150937500 System 4 14906718750System 4 14906718750 smss.exe 864 937500smss.exe 864 937500 csrss.exe 916 1752187500 winlogon.exe 940 72812500csrss.exe 916 1752187500winlogon.exe 940 72812500 services.exe 1024 324236406250 lsass.exe 1044 10099062500services.exe 1024 324236406250 svchost.exe 1236 35468750 svchost.exe 1304 6174687500 svchost.exe 1480 198943593750 svchost.exe 1524 35156250 svchost.exe 1636 1412656250 svchost.exe 1688 494843750 spoolsv.exe 1860 45312500 DhMachineSvc.exe 2040 23593750 jqs.exe 200 11605000000 NTFSWatcher.exe 248 15625000 OmniAddrService.exe 268 86406250 pcas.exe 396 172187500 nssm.exe 696 2968750 TeamViewer_Service.exe 772 172343750 winvnc4.exe 844 78750000 svchost.exe 880 151718750 alg.exe 3208 56093750lsass.exe 1044 10099062500svchost.exe 1236 35468750 wmiprvse.exe 5184 2500000svchost.exe 1304 6174687500svchost.exe 1480 198943125000svchost.exe 1524 35156250svchost.exe 1636 1412656250svchost.exe 1688 494843750spoolsv.exe 1860 45312500DhMachineSvc.exe 2040 23593750jqs.exe 200 11605000000GoogleUpdate.exe 208 105312500NTFSWatcher.exe 248 15625000OmniAddrService.exe 268 86406250pcas.exe 396 172187500nssm.exe 696 2968750 salt-minion.exe 716 79062500salt-minion.exe 716 79062500TeamViewer_Service.exe 772 172343750winvnc4.exe 844 78750000svchost.exe 880 151718750explorer.exe 1452 7501250000 TSVNCache.exe 2496 114531250 ctfmon.exe 2540 82343750 chrome.exe 2556 25053125000 RocketDock.exe 2564 411406250 Xshell.exe 5200 12957656250 mstsc.exe 8468 227500000 iexplore.exe 7672 13281250 cmd.exe 9404 312500 sublime_text.exe 8920 131093750 notepad.exe 2248 1718750TSVNCache.exe 2496 114531250ctfmon.exe 2540 82343750chrome.exe 2556 25053125000 chrome.exe 3880 24531250 chrome.exe 3872 52500000 chrome.exe 2020 331093750 chrome.exe 1028 35937500 chrome.exe 196 37187500 chrome.exe 184 55625000 chrome.exe 2736 37656250 chrome.exe 2752 1755781250 chrome.exe 2772 83281250 chrome.exe 2976 258125000 SogouFlash.exe 3580 640468750 SogouCloud.exe 3488 115625000 SGImeGuard.exe 4300 24218750 chrome.exe 3700 40312500 chrome.exe 9148 3741406250 chrome.exe 8496 7201250000 chrome.exe 6840 200312500 SogouSmartInfo.exe 9852 468750RocketDock.exe 2564 411406250alg.exe 3208 56093750chrome.exe 3880 24531250chrome.exe 3872 52500000chrome.exe 2020 331093750chrome.exe 1028 35937500chrome.exe 196 37187500chrome.exe 184 55625000chrome.exe 2736 37656250chrome.exe 2752 1755781250chrome.exe 2772 83281250chrome.exe 2976 258125000TaobaoProtect.exe 3772 27562812500conime.exe 388 59218750SogouFlash.exe 3580 640468750SogouCloud.exe 3488 115625000SGImeGuard.exe 4300 24218750Xshell.exe 5200 12957656250chrome.exe 3700 40312500aliwssv.exe 7160 46875000TM.exe 9144 2396250000chrome.exe 9148 3741250000Alipaybsm.exe 9536 73593750chrome.exe 8496 7199843750mstsc.exe 8468 227500000iexplore.exe 7672 13281250 iexplore.exe 7256 148593750iexplore.exe 7256 148437500cmd.exe 9404 312500 python.exe 9048 1875000sublime_text.exe 8920 127968750 plugin_host.exe 9840 32031250plugin_host.exe 9840 30625000 cmd.exe 6384 156250python.exe 9048 1875000notepad.exe 2248 1718750chrome.exe 6840 200312500SogouSmartInfo.exe 9852 468750cmd.exe 6384 156250 python.exe 9584 10312500python.exe 9584 1093750wmiprvse.exe 5184 781250
上面的从左到右分别是
进程名
,pid
,cpu的运行时间
方式二:
import win32pdh, string, win32api def procids(): #each instance is a process, you can have multiple processes w/same name junk, instances = win32pdh.EnumObjectItems(None,None,'process', win32pdh.PERF_DETAIL_WIZARD) proc_ids=[] proc_dict={} for instance in instances: if instance in proc_dict: proc_dict[instance] = proc_dict[instance] + 1 else: proc_dict[instance]=0 for instance, max_instances in proc_dict.items(): for inum in xrange(max_instances+1): hq = win32pdh.OpenQuery() # initializes the query handle path = win32pdh.MakeCounterPath( (None,'process',instance, None, inum,'ID Process') ) counter_handle=win32pdh.AddCounter(hq, path) win32pdh.CollectQueryData(hq) #collects data for the counter type, val = win32pdh.GetFormattedCounterValue(counter_handle, win32pdh.PDH_FMT_LONG) proc_ids.append((instance,str(val))) win32pdh.CloseQuery(hq) proc_ids.sort() return proc_ids print procids()
运行结果:
[(u'Alipaybsm', '9536'), (u'DhMachineSvc', '2040'), (u'GoogleUpdate', '208'), (u'Idle', '0'), (u'NTFSWatcher', '248'), (u'OmniAddrService', '268'), (u'RocketDock', '2564'), (u'SGImeGuard', '4300'), (u'SogouCloud', '3488'), (u'SogouFlash', '3580'), (u'SogouSmartInfo', '9852'), (u'System', '4'), (u'TM', '9144'), (u'TSVNCache', '2496'), (u'TaobaoProtect', '3772'), (u'TeamViewer_Service', '772'), (u'Xshell', '5200'), (u'_Total', '0'), (u'alg', '3208'), (u'aliwssv', '7160'), (u'chrome', '1028'), (u'chrome', '184'), (u'chrome', '196'), (u'chrome', '2020'), (u'chrome', '2556'), (u'chrome', '2736'), (u'chrome', '2752'), (u'chrome', '2772'), (u'chrome', '2976'), (u'chrome', '3700'), (u'chrome', '3872'), (u'chrome', '3880'), (u'chrome', '6840'), (u'chrome', '8496'), (u'chrome', '9148'), (u'cmd', '9404'), (u'cmd', '9776'), (u'conime', '388'), (u'csrss', '916'), (u'ctfmon', '2540'), (u'explorer', '1452'), (u'iexplore', '7256'), (u'iexplore', '7672'), (u'jqs', '200'), (u'lsass', '1044'), (u'mstsc', '8468'), (u'notepad', '2248'), (u'nssm', '696'), (u'pcas', '396'), (u'plugin_host', '9840'), (u'python', '3540'), (u'python', '9048'), (u'salt-minion', '716'), (u'services', '1024'), (u'smss', '864'), (u'spoolsv', '1860'), (u'sublime_text', '8920'), (u'svchost', '1236'), (u'svchost', '1304'), (u'svchost', '1480'), (u'svchost', '1524'), (u'svchost', '1636'), (u'svchost', '1688'), (u'svchost', '880'), (u'winlogon', '940'), (u'winvnc4', '844')] [Finished in 0.3s]
获得 一个
进程名
,进程Id
元组的列表
方式三:
# http://code.activestate.com/recipes/305279/ """ Enumerates active processes as seen under windows Task Manager on Win NT/2k/XP using PSAPI.dll (new api for processes) and using ctypes.Use it as you please. Based on information from http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q175030&ID=KB;EN-US;Q175030 By Eric Koome email ekoome@yahoo.com license GPL """from ctypes import * #PSAPI.DLLpsapi = windll.psapi#Kernel32.DLLkernel = windll.kernel32 def EnumProcesses(): arr = c_ulong * 256 lpidProcess= arr() cb = sizeof(lpidProcess) cbNeeded = c_ulong() hModule = c_ulong() count = c_ulong() modname = c_buffer(30) PROCESS_QUERY_INFORMATION = 0x0400 PROCESS_VM_READ = 0x0010 #Call Enumprocesses to get hold of process id's psapi.EnumProcesses(byref(lpidProcess), cb, byref(cbNeeded)) #Number of processes returned nReturned = cbNeeded.value/sizeof(c_ulong()) pidProcess = [i for i in lpidProcess][:nReturned] for pid in pidProcess: #Get handle to the process based on PID hProcess = kernel.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid) if hProcess: psapi.EnumProcessModules(hProcess, byref(hModule), sizeof(hModule), byref(count)) psapi.GetModuleBaseNameA(hProcess, hModule.value, modname, sizeof(modname)) print "".join([ i for i in modname if i != '\x00']) #-- Clean up for i in range(modname._length_): modname[i]='\x00' kernel.CloseHandle(hProcess) if __name__ == '__main__': EnumProcesses()
运行结果:
smss.exewinlogon.exeservices.exelsass.exesvchost.exesvchost.exesvchost.exespoolsv.exeDhMachineSvc.exejqs.exeGoogleUpdate.exeNTFSWatcher.exeOmniAddrService.exepcas.exenssm.exesalt-minion.exeTeamViewer_Service.exeWinVNC4.exesvchost.exeExplorer.EXETSVNCache.exectfmon.exechrome.exeRocketDock.exechrome.exechrome.exechrome.exechrome.exechrome.exechrome.exechrome.exechrome.exechrome.exechrome.exeTaobaoProtect.execonime.exeSogouFlash.exeSogouCloud.exeSGImeGuard.exeXshell.exechrome.exealiwssv.exeTM.exechrome.exeAlipaybsm.exechrome.exemstsc.exeiexplore.exeiexplore.execmd.exesublime_text.exeplugin_host.exepython.exeNOTEPAD.EXEchrome.exechrome.exeSogouSmartInfo.execmd.exepython.exe
通过交互模式,使用WMI取得进程:
# http://mail.python.org/pipermail/python-win32/2003-December/001482.html>>> import wmi>>> processes = wmi.WMI().InstancesOf('Win32_Process')>>> len(processes)41>>> [process.Properties_('Name').Value for process in processes] # getthe process names [u'System Idle Process', u'System', u'SMSS.EXE', u'CSRSS.EXE', u'WINLOGON.EXE', u'SERVICES.EXE', u'LSASS.EXE', u'SVCHOST.EXE', u'SVCHOST.EXE', u'SVCHOST.EXE', u'SVCHOST.EXE', u'SPOOLSV.EXE', u'ati2evxx.exe', u'BAsfIpM.exe', u'defwatch.exe', u'inetinfo.exe', u'mdm.exe', u'rtvscan.exe', u'SCARDSVR.EXE', u'WLTRYSVC.EXE', u'BCMWLTRY.EXE', u'EXPLORER.EXE', u'Apoint.exe', u'carpserv.exe', u'atiptaxx.exe', u'quickset.exe', u'DSentry.exe', u'Directcd.exe', u'vptray.exe', u'ApntEx.exe', u'FaxCtrl.exe', u'digstream.exe', u'CTFMON.EXE', u'wuauclt.exe', u'IEXPLORE.EXE', u'Pythonwin.exe', u'MMC.EXE', u'OUTLOOK.EXE', u'LineMgr.exe', u'SAPISVR.EXE', u'WMIPRVSE.EXE'] # Here is how to get a single process and get its PID. >>> p = wmi.WMI().ExecQuery('select * from Win32_Process where Name="Pythonwin.exe"')>>> [prop.Name for prop in p[0].Properties_] # let's look at all theprocess property names [u'Caption', u'CommandLine', u'CreationClassName', u'CreationDate', u'CSCreationClassName', u'CSName', u'Description', u'ExecutablePath', u'ExecutionState', u'Handle', u'HandleCount', u'InstallDate', u'KernelModeTime', u'MaximumWorkingSetSize', u'MinimumWorkingSetSize', u'Name', u'OSCreationClassName', u'OSName', u'OtherOperationCount', u'OtherTransferCount', u'PageFaults', u'PageFileUsage', u'ParentProcessId', u'PeakPageFileUsage', u'PeakVirtualSize', u'PeakWorkingSetSize', u'Priority', u'PrivatePageCount', u'ProcessId', u'QuotaNonPagedPoolUsage', u'QuotaPagedPoolUsage', u'QuotaPeakNonPagedPoolUsage', u'QuotaPeakPagedPoolUsage', u'ReadOperationCount', u'ReadTransferCount', u'SessionId', u'Status', u'TerminationDate', u'ThreadCount', u'UserModeTime', u'VirtualSize', u'WindowsVersion', u'WorkingSetSize', u'WriteOperationCount', u'WriteTransferCount']>>> p[0].Properties_('ProcessId').Value # get our ProcessId928
方式四:
此方法可以跨平台,不过需要在安装psutil
包.
import osimport psutilimport time logPath = r'some\path\proclogs'if not os.path.exists(logPath): os.mkdir(logPath) separator = "-" * 80format = "%7s %7s %12s %12s %30s, %s"format2 = "%7.4f %7.2f %12s %12s %30s, %s"while 1: # psutil.get_process_list() 方法已经废弃,可以使用psutil.process_iter()迭代器 procs = psutil.get_process_list() procs = sorted(procs, key=lambda proc: proc.name) logPath = r'some\path\proclogs\procLog%i.log' % int(time.time()) f = open(logPath, 'w') f.write(separator + "\n") f.write(time.ctime() + "\n") f.write(format % ("%CPU", "%MEM", "VMS", "RSS", "NAME", "PATH")) f.write("\n") for proc in procs: cpu_percent = proc.get_cpu_percent() mem_percent = proc.get_memory_percent() rss, vms = proc.get_memory_info() rss = str(rss) vms = str(vms) name = proc.name path = proc.path f.write(format2 % (cpu_percent, mem_percent, vms, rss, name, path)) f.write("\n\n") f.close() print "Finished log update!" time.sleep(300) print "writing new log data!"
以上实现一个类似top的工具。
转自 http://www.blog.pythonlibrary.org/2010/10/03/how-to-find-and-list-all-running-processes-with-python/