linux應該有很多方法可以獲取進程的cpu和內存信息,但windows貌似之前接觸的是psutil,后來查了一些資料發現wmi也能夠獲取進程的信息,但貌似效率不太高,應該可以做監控等性能要求不太高的情況
下載wmi,這個網上很多方法和途徑,我是用easyinstall來安裝,這個不詳細說明了
直接附上代碼:
import wmi from win32com.client import GetObject import win32gui,time mywmi = GetObject("winmgmts:") # allProcess = mywmi.ExecQuery("select * from Win32_Process") # for i in allProcess: # pid = i.Properties_("ProcessID") # print pid # network = mywmi.ExecQuery("select Processor, _Total, Processor Time from PerformanceCounter") # print network # for i in network: # print i.Properties_("Processor") mywql= mywmi.ExecQuery("SELECT * FROM Win32_PerfFormattedData_PerfProc_Process where PercentPrivilegedTime>10") def getPrcessInfo(wql): while 1: for j in wql: #print j.Properties_("PercentPrivilegedTime").__int__() ##print j.Properties_("name").__str__()+" "+j.Properties_("IDProcess").__str__()+" "+j.Properties_("PercentPrivilegedTime").__str__() if j.Properties_("name").__str__()!= "_Total" and j.Properties_("name").__str__()!="Idle": print j.Properties_("name") print j.Properties_("PercentPrivilegedTime").__int__() print j.Properties_("WorkingSet").__int__() time.sleep(1) #return 1 #break ##print ":)" getProcessInfo(mysql)
編碼方式停留在初學的基礎上,后續需要改進,j.Properties_("屬性")得出的是一個實例,所以需要轉換成相應的格式;
詳細的屬性可以參考https://msdn.microsoft.com/en-us/library/aa394277(VS.85).aspx
個人感覺wmi功能挺強大的,能搞通的話,應該可以玩轉windows(有點誇張了)