如何在Python中获取当前的CPU和RAM使用情况?

在Python中获取当前系统状态(当前CPU,RAM,可用磁盘空间等)的首选方式是什么? * nix和Windows平台的奖励积分。

似乎有几种可能的方法从我的search中提取:

  1. 使用像PSI (目前似乎不积极开发,不支持多平台)或类似pystatgrab (自2007年以来似乎没有任何活动,似乎也不支持Windows)的库。

  2. 对于Windows平台,使用特定于平台的代码,例如在* nix系统中使用os.popen("ps")或类似命令,在ctypes.windll.kernel32 MEMORYSTATUS (请参阅ActiveState上的此配方 )。 可以将Python类与所有这些代码片段放在一起。

这不是说那些方法不好,但是已经有了一个很好的支持多平台的方法来做同样的事情吗?

psutil库会给你一些系统信息(CPU /内存使用情况)在各种平台上:

psutil是一个模块,提供了一个接口,通过使用Python以便携的方式检索有关运行进程和系统利用率(CPU,内存)的信息,实现了诸如ps,top和Windows任务pipe理器等工具提供的许多function。

它目前支持Linux版本,Windows,OSX,Sun Solaris,FreeBSD,OpenBSD和NetBSD,32位和64位体系结构,Python版本从2.6到3.5(Python 2.4和2.5的用户可以使用2.1.3版本)。

使用psutil库 。 对于我在Ubuntu上,pip安装了0.4.3。 你可以通过做检查你的版本的psutil

 from __future__ import print_function import psutil print(psutil.__versi‌​on__) 

在Python中。

获取一些内存和CPU统计信息:

 from __future__ import print_function import psutil print(psutil.cpu_percent()) print(psutil.virtual_memory()) # physical memory usage 

我也喜欢做:

 import os import psutil pid = os.getpid() py = psutil.Process(pid) memoryUse = py.memory_info()[0]/2.**30 # memory use in GB...I think print('memory use:', memoryUse) 

这给出了Python脚本的当前内存使用情况。

在4.3.0和0.5.0的pypi页面上有更深入的例子。

对于Ubuntu 16和14,从pip安装给我版本4.3.0,它没有phymem_usage()方法。 要获得0.5.0,请下载tar.gz文件 ,然后执行

 tar -xvzf psutil-0.5.0.tar.gz‌​ cd psutil-0.5.0 sudo python setup.py install 

这是我刚才放在一起的东西,它只是窗口,但可以帮助你得到你需要做的一部分。

派生自:“for sys available mem” http://msdn2.microsoft.com/en-us/library/aa455130.aspx

“个人进程信息和python脚本示例” http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true

注:WMI接口/进程也可用于执行类似的任务,我不在这里使用它,因为当前的方法覆盖了我的需求,但如果有一天需要扩展或改进,那么可能需要调查WMI工具。

WMI for python:

http://tgolden.sc.sabren.com/python/wmi.html

代码:

 ''' Monitor window processes derived from: >for sys available mem http://msdn2.microsoft.com/en-us/library/aa455130.aspx > individual process information and python script examples http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true NOTE: the WMI interface/process is also available for performing similar tasks I'm not using it here because the current method covers my needs, but if someday it's needed to extend or improve this module, then may want to investigate the WMI tools available. WMI for python: http://tgolden.sc.sabren.com/python/wmi.html ''' __revision__ = 3 import win32com.client from ctypes import * from ctypes.wintypes import * import pythoncom import pywintypes import datetime class MEMORYSTATUS(Structure): _fields_ = [ ('dwLength', DWORD), ('dwMemoryLoad', DWORD), ('dwTotalPhys', DWORD), ('dwAvailPhys', DWORD), ('dwTotalPageFile', DWORD), ('dwAvailPageFile', DWORD), ('dwTotalVirtual', DWORD), ('dwAvailVirtual', DWORD), ] def winmem(): x = MEMORYSTATUS() # create the structure windll.kernel32.GlobalMemoryStatus(byref(x)) # from cytypes.wintypes return x class process_stats: '''process_stats is able to provide counters of (all?) the items available in perfmon. Refer to the self.supported_types keys for the currently supported 'Performance Objects' To add logging support for other data you can derive the necessary data from perfmon: --------- perfmon can be run from windows 'run' menu by entering 'perfmon' and enter. Clicking on the '+' will open the 'add counters' menu, From the 'Add Counters' dialog, the 'Performance object' is the self.support_types key. --> Where spaces are removed and symbols are entered as text (Ex. # == Number, % == Percent) For the items you wish to log add the proper attribute name in the list in the self.supported_types dictionary, keyed by the 'Performance Object' name as mentioned above. --------- NOTE: The 'NETFramework_NETCLRMemory' key does not seem to log dotnet 2.0 properly. Initially the python implementation was derived from: http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true ''' def __init__(self,process_name_list=[],perf_object_list=[],filter_list=[]): '''process_names_list == the list of all processes to log (if empty log all) perf_object_list == list of process counters to log filter_list == list of text to filter print_results == boolean, output to stdout ''' pythoncom.CoInitialize() # Needed when run by the same process in a thread self.process_name_list = process_name_list self.perf_object_list = perf_object_list self.filter_list = filter_list self.win32_perf_base = 'Win32_PerfFormattedData_' # Define new datatypes here! self.supported_types = { 'NETFramework_NETCLRMemory': [ 'Name', 'NumberTotalCommittedBytes', 'NumberTotalReservedBytes', 'NumberInducedGC', 'NumberGen0Collections', 'NumberGen1Collections', 'NumberGen2Collections', 'PromotedMemoryFromGen0', 'PromotedMemoryFromGen1', 'PercentTimeInGC', 'LargeObjectHeapSize' ], 'PerfProc_Process': [ 'Name', 'PrivateBytes', 'ElapsedTime', 'IDProcess',# pid 'Caption', 'CreatingProcessID', 'Description', 'IODataBytesPersec', 'IODataOperationsPersec', 'IOOtherBytesPersec', 'IOOtherOperationsPersec', 'IOReadBytesPersec', 'IOReadOperationsPersec', 'IOWriteBytesPersec', 'IOWriteOperationsPersec' ] } def get_pid_stats(self, pid): this_proc_dict = {} pythoncom.CoInitialize() # Needed when run by the same process in a thread if not self.perf_object_list: perf_object_list = self.supported_types.keys() for counter_type in perf_object_list: strComputer = "." objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator") objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2") query_str = '''Select * from %s%s''' % (self.win32_perf_base,counter_type) colItems = objSWbemServices.ExecQuery(query_str) # "Select * from Win32_PerfFormattedData_PerfProc_Process")# changed from Win32_Thread if len(colItems) > 0: for objItem in colItems: if hasattr(objItem, 'IDProcess') and pid == objItem.IDProcess: for attribute in self.supported_types[counter_type]: eval_str = 'objItem.%s' % (attribute) this_proc_dict[attribute] = eval(eval_str) this_proc_dict['TimeStamp'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.') + str(datetime.datetime.now().microsecond)[:3] break return this_proc_dict def get_stats(self): ''' Show process stats for all processes in given list, if none given return all processes If filter list is defined return only the items that match or contained in the list Returns a list of result dictionaries ''' pythoncom.CoInitialize() # Needed when run by the same process in a thread proc_results_list = [] if not self.perf_object_list: perf_object_list = self.supported_types.keys() for counter_type in perf_object_list: strComputer = "." objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator") objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2") query_str = '''Select * from %s%s''' % (self.win32_perf_base,counter_type) colItems = objSWbemServices.ExecQuery(query_str) # "Select * from Win32_PerfFormattedData_PerfProc_Process")# changed from Win32_Thread try: if len(colItems) > 0: for objItem in colItems: found_flag = False this_proc_dict = {} if not self.process_name_list: found_flag = True else: # Check if process name is in the process name list, allow print if it is for proc_name in self.process_name_list: obj_name = objItem.Name if proc_name.lower() in obj_name.lower(): # will log if contains name found_flag = True break if found_flag: for attribute in self.supported_types[counter_type]: eval_str = 'objItem.%s' % (attribute) this_proc_dict[attribute] = eval(eval_str) this_proc_dict['TimeStamp'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.') + str(datetime.datetime.now().microsecond)[:3] proc_results_list.append(this_proc_dict) except pywintypes.com_error, err_msg: # Ignore and continue (proc_mem_logger calls this function once per second) continue return proc_results_list def get_sys_stats(): ''' Returns a dictionary of the system stats''' pythoncom.CoInitialize() # Needed when run by the same process in a thread x = winmem() sys_dict = { 'dwAvailPhys': x.dwAvailPhys, 'dwAvailVirtual':x.dwAvailVirtual } return sys_dict if __name__ == '__main__': # This area used for testing only sys_dict = get_sys_stats() stats_processor = process_stats(process_name_list=['process2watch'],perf_object_list=[],filter_list=[]) proc_results = stats_processor.get_stats() for result_dict in proc_results: print result_dict import os this_pid = os.getpid() this_proc_results = stats_processor.get_pid_stats(this_pid) print 'this proc results:' print this_proc_results 

http://monkut.webfactional.com/blog/archive/2009/1/21/windows-process-memory-logging-python

下面的代码,没有外部库为我工作。 我在Python 2.7.9testing

CPU使用率

 import os CPU_Pct=str(round(float(os.popen('''grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage }' ''').readline()),2)) #print results print("CPU Usage = " + CPU_Pct) 

和Ram的使用,总计,使用和免费

 import os mem=str(os.popen('free -t -m').readlines()) """ Get a whole line of memory output, it will be something like below [' total used free shared buffers cached\n', 'Mem: 925 591 334 14 30 355\n', '-/+ buffers/cache: 205 719\n', 'Swap: 99 0 99\n', 'Total: 1025 591 434\n'] So, we need total memory, usage and free memory. We should find the index of capital T which is unique at this string """ T_ind=mem.index('T') """ Than, we can recreate the string with this information. After T we have, "Total: " which has 14 characters, so we can start from index of T +14 and last 4 characters are also not necessary. We can create a new sub-string using this information """ mem_G=mem[T_ind+14:-4] """ The result will be like 1025 603 422 we need to find first index of the first space, and we can start our substring from from 0 to this index number, this will give us the string of total memory """ S1_ind=mem_G.index(' ') mem_T=mem_G[0:S1_ind] """ Similarly we will create a new sub-string, which will start at the second value. The resulting string will be like 603 422 Again, we should find the index of first space and than the take the Used Memory and Free memory. """ mem_G1=mem_G[S1_ind+8:] S2_ind=mem_G1.index(' ') mem_U=mem_G1[0:S2_ind] mem_F=mem_G1[S2_ind+8:] print 'Summary = ' + mem_G print 'Total Memory = ' + mem_T +' MB' print 'Used Memory = ' + mem_U +' MB' print 'Free Memory = ' + mem_F +' MB' 

“…当前系统状态(当前的CPU,RAM,可用磁盘空间等)”和“* nix和Windows平台”可以很难实现。

操作系统在pipe理这些资源方面有着根本的不同。 事实上,他们在核心概念上有所不同,例如定义什么是系统,什么是应用程序时间。

“可用磁盘空间”? 什么是“磁盘空间”? 所有设备的所有分区? 那么多引导环境下的外部分区呢?

我不认为在Windows和* nix之间有足够的共识,这使得这一点成为可能。 事实上,在各种称为Windows的操作系统之间可能甚至没有达成共识。 是否有一个适用于XP和Vista的Windows API?

单用于仅使用stdlib依赖性的RAM使用情况:

 import os tot_m, used_m, free_m = map(int, os.popen('free -t -m').readlines()[-1].split()[1:]) 

您可以使用psutil或psmem和子stream程示例代码

 import subprocess cmd = subprocess.Popen(['sudo','./ps_mem'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) out,error = cmd.communicate() memory = out.splitlines() 

参考http://techarena51.com/index.php/how-to-install-python-3-and-flask-on-linux/

https://github.com/Leo-g/python-flask-cmd

我不相信有一个支持良好的多平台库。 请记住,Python本身是用C语言编写的,所以任何一个库都只是根据你上面的build议做出明智的决定,决定运行哪个操作系统特定的代码片段。