2008-11-09 94 views
200

在Python中獲取當前系統狀態(當前CPU,RAM,可用磁盤空間等)的首選方式是什麼? * nix和Windows平臺的獎勵積分。如何在Python中獲取當前的CPU和RAM使用情況?

似乎有提取,從我搜索的一些可能的方式:

  1. 使用庫如PSI(目前似乎不積極地開發和不支持多平臺)或類似pystatgrab什麼(自2007年以來似乎再也沒有活動,並且不支持Windows)。

  2. 使用特定於平臺的代碼,如使用ctypes.windll.kernel32一個os.popen("ps")或爲* nix系統相似,MEMORYSTATUS(見this recipe on ActiveState)針對Windows平臺。人們可以將Python類與所有這些代碼片段放在一起。

這不是說那些方法不好,但是已經有了一個很好的支持多平臺的方法來做同樣的事情嗎?

+0

你可以建立自己的multiplatfor m庫通過使用動態導入:「if sys.platform =='win32':import win_sysstatus as sysstatus;其他「... – 2008-11-10 00:02:01

+0

在App Engine上也有很酷的功能 – 2011-03-30 15:16:11

+5

爲什麼你接受一個Unix特定的答案?我建議你把接受的答案改爲@ JonCage's。看看有多少個upvotes - 社區同意我的看法 – 2012-10-02 19:40:30

回答

244

The psutil library會給你各種平臺的一些系統信息(CPU /內存使用率) :

psutil是提供通過使用Python,落實如ps,頂部和Windows任務管理器工具提供了許多功能取回與在便攜方式運行的進程和系統利用率(CPU,內存)的信息的接口的模塊。

它目前支持Linux版本,Windows,OSX,Sun Solaris,FreeBSD,OpenBSD和NetBSD,都是32位和64位體系結構,Python版本從2.6到3.5(Python 2.4和2.5的用戶可能使用2.1。 3版)。

-1

我不相信有一個良好支持的多平臺庫可用。請記住,Python本身是用C語言編寫的,因此任何庫都將根據您上面的建議做出關於哪個OS特定代碼片段運行的明智決定。

3

「...當前系統狀態(當前CPU,RAM,可用磁盤空間等)」和「* nix和Windows平臺」可能是一個難以實現的組合。

操作系統在管理這些資源的方式上有着根本性的不同。事實上,他們在覈心概念方面有所不同,例如定義什麼是系統,什麼是應用程序時間。

「可用磁盤空間」?什麼算作「磁盤空間?」所有設備的所有分區?多引導環境下的外部分區怎麼樣?

我不認爲Windows和* nix之間有足夠明確的共識,這使得這成爲可能。事實上,在稱爲Windows的各種操作系統之間可能甚至沒有達成共識。是否有一個適用於XP和Vista的Windows API?

8

這是前段時間我放在一起的東西,它只是Windows,但可以幫助您獲得所需的部分內容。

來源於: 「可用MEM SYS」 http://msdn2.microsoft.com/en-us/library/aa455130.aspx

「單個工序信息和Python腳本示例」 http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true

注:WMI接口/過程也可用於執行類似任務 我沒有在這裏使用它,因爲當前的方法覆蓋了我的需求,但是如果有一天需要擴展或改進,那麼可能需要調查WMI工具。

WMI的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

24

使用psutil library。對於我在Ubuntu上,pip安裝了0.4.3。你可以通過做

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腳本的。

上有pypi page for 4.3.00.5.0一些更深入的例子。

對於Ubuntu的16和14,從PIP安裝給我的版本4.3.0,它不具有phymem_usage()方法。獲得0.5.0,download the tar.gz file,然後做

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

下面的代碼,沒有外部庫爲我工作。我在Python 2.7測試。9

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' 
5

一襯裏只有STDLIB依賴性RAM用法:

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