2008-11-09 11 views
200

पायथन में वर्तमान सिस्टम स्थिति (वर्तमान सीपीयू, रैम, फ्री डिस्क स्पेस, आदि) प्राप्त करने का आपका पसंदीदा तरीका क्या है? * निक्स और विंडोज प्लेटफार्मों के लिए बोनस अंक।पायथन में वर्तमान सीपीयू और रैम उपयोग कैसे प्राप्त करें?

  1. pystatgrab की तरह एक पुस्तकालय PSI जैसे (जो वर्तमान में सक्रिय रूप से विकसित नहीं लगता है और कई प्लेटफ़ॉर्म पर समर्थित नहीं) या कुछ का उपयोग करना:

    वहाँ निकालने कि मेरी खोज से के कुछ संभव तरीके हो रहा है (2007 के बाद से कोई गतिविधि नहीं लगता है और विंडोज के लिए कोई समर्थन नहीं है)।

  2. जैसे Windows प्लेटफॉर्म के लिए एक os.popen("ps") या * nix प्रणालियों के लिए समान और ctypes.windll.kernel32 में MEMORYSTATUS का उपयोग कर (this recipe on ActiveState देखें) के रूप में मंच विशिष्ट कोड का उपयोग करना। कोई भी उन कोड स्निपेट के साथ एक पायथन कक्षा को एक साथ रख सकता है।

ऐसा नहीं है कि वे विधियां खराब हैं लेकिन क्या पहले से ही एक अच्छी तरह से समर्थित, बहु-मंच तरीका एक ही काम करने का तरीका है?

+0

आप अपना खुद का बहुउद्देशीय बना सकते हैं गतिशील आयात का उपयोग करके एम लाइब्रेरी: "यदि sys.platform == 'win32': sysstatus के रूप में win_sysstatus आयात करें; अन्यथा ... –

+0

यह कुछ अच्छा होगा जो ऐप इंजन पर भी काम करता है। –

+5

आपने यूनिक्स-विशिष्ट उत्तर क्यों स्वीकार किया? मेरा सुझाव है कि आप @ JonCage के स्वीकृत उत्तर को बदल दें। उपरोक्त संख्याओं को देखें - समुदाय मेरे साथ सहमत है। –

उत्तर

244

The psutil library आप प्लेटफार्मों की एक किस्म पर कुछ सिस्टम जानकारी (सीपीयू/स्मृति उपयोग) दे देंगे :

psutil एक मॉड्यूल है जो पाइथन का उपयोग करके पोर्टेबल तरीके से चल रही प्रक्रियाओं और सिस्टम उपयोग (सीपीयू, मेमोरी) पर जानकारी पुनर्प्राप्त करने के लिए एक इंटरफ़ेस प्रदान करता है, जो पीएस, टॉप और विंडोज टास्क मैनेजर जैसे टूल द्वारा प्रदान की जाने वाली कई कार्यक्षमताओं को लागू करता है।

यह वर्तमान में 32-बिट और 64-बिट आर्किटेक्चर दोनों में लिनक्स, विंडोज़, ओएसएक्स, सन सोलारिस, फ्रीबीएसडी, ओपनबीएसडी और नेटबीएसडी का समर्थन करता है, जिसमें पाइथन संस्करण 2.6 से 3.5 तक (पायथन 2.4 और 2.5 के उपयोगकर्ता 2.1 का उपयोग कर सकते हैं। 3 संस्करण)।

+3

यह पुस्तकालय अच्छा और उपयोगी लगता है, धन्यवाद – riviera

+23

ओएसएक्स पर मेरे लिए काम किया: '$ पीआईपी psutil स्थापित करें; '> आयात psutil; psutil.cpu_percent() 'और' >>> psutil.virtual_memory() 'जो एक अच्छा vmem ऑब्जेक्ट देता है:' vmem (कुल = 8589934592L, उपलब्ध = 4073336832L, प्रतिशत = 52.6, प्रयुक्त = 5022085120L, निशुल्क = 3560255488L, सक्रिय = 2817949696L , निष्क्रिय = 513081344 एल, वायर्ड = 16 91054080 एल) ' – hobs

+4

psutil पुस्तकालय के बिना कोई ऐसा कैसे करेगा? – BigBrownBear00

-1

मुझे विश्वास नहीं है कि एक अच्छी तरह से समर्थित बहु-मंच लाइब्रेरी उपलब्ध है। याद रखें कि पाइथन स्वयं सी में लिखा गया है, इसलिए कोई भी लाइब्रेरी बस एक ओएस-विशिष्ट कोड स्निपेट चलाने के बारे में एक स्मार्ट निर्णय लेने जा रही है, जैसा आपने ऊपर बताया था।

3

"... वर्तमान सिस्टम स्थिति (वर्तमान सीपीयू, रैम, फ्री डिस्क स्पेस, आदि)" और "* निक्स और विंडोज प्लेटफ़ॉर्म" प्राप्त करने के लिए एक कठिन संयोजन हो सकता है।

ऑपरेटिंग सिस्टम इन संसाधनों को प्रबंधित करने के तरीके में मूल रूप से भिन्न हैं। दरअसल, वे मूल अवधारणाओं में भिन्न होते हैं जैसे परिभाषित करना कि सिस्टम के रूप में क्या मायने रखता है और आवेदन समय के रूप में क्या मायने रखता है।

"फ्री डिस्क स्पेस"? "डिस्क स्पेस" के रूप में क्या मायने रखता है? सभी उपकरणों के सभी विभाजन? बहु-बूट वातावरण में विदेशी विभाजन के बारे में क्या?

मुझे नहीं लगता कि विंडोज और * निक्स के बीच पर्याप्त सहमति है जो इसे संभव बनाता है। दरअसल, विंडोज़ नामक विभिन्न ऑपरेटिंग सिस्टम के बीच कोई आम सहमति भी नहीं हो सकती है। क्या एक एकल विंडोज एपीआई है जो एक्सपी और विस्टा दोनों के लिए काम करता है?

+4

'df -h' विंडोज़ और * निक्स पर" डिस्क स्पेस "प्रश्न का उत्तर देता है। – jfs

+3

@ जेएफएसबीस्टियन: कौन सा विंडोज़? मुझे एक 'डीएफ' पहचाना नहीं गया है ... विंडोज एक्सपी प्रो से त्रुटि संदेश। मुझे क्या याद आ रहा है? –

+3

आप विंडोज़ पर भी नए प्रोग्राम इंस्टॉल कर सकते हैं। – jfs

8

यहां कुछ ऐसा है जो मैंने थोड़ी देर पहले रखा था, यह केवल खिड़कियां है लेकिन आपको जो कुछ करने की आवश्यकता है उसका हिस्सा पाने में आपकी सहायता कर सकती है।

से व्युत्पन्न: http://msdn2.microsoft.com/en-us/library/aa455130.aspx

"व्यक्तिगत प्रक्रिया की जानकारी और अजगर स्क्रिप्ट उदाहरण" http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true

नोट "उपलब्ध मेम sys के लिए" : WMI इंटरफ़ेस/प्रक्रिया भी समान कार्य प्रदर्शन के लिए उपलब्ध है मैं इसे यहां उपयोग नहीं कर रहा हूं क्योंकि वर्तमान विधि मेरी ज़रूरतों को पूरा करती है, लेकिन अगर किसी दिन इसे विस्तारित या सुधारने की आवश्यकता है, तो वह डब्लूएमआई टूल्स की एक जमानती जांच कर सकता है।

अजगर के लिए WMI:

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

+0

आपका लिंक टूटा हुआ है। –

+0

हाँ। लिंक बी है अब रोके गए –

+0

GlobalMemoryStatus के बजाय GlobalMemoryStatusEx का उपयोग करें क्योंकि पुराना कोई खराब मान वापस कर सकता है। – phobie

24

उपयोग psutil library साथ psutil या psmem उपयोग कर सकते हैं। उबंटू पर मेरे लिए, पाइप 0.4.3 स्थापित किया गया। आप पाइथन में

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

करके psutil के अपने संस्करण की जांच कर सकते हैं।

कुछ स्मृति और 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) 

जो अपने अजगर स्क्रिप्ट की वर्तमान स्मृति उपयोग देता है।

pypi page for 4.3.0 और 0.5.0 पर कुछ और गहन उदाहरण हैं।

उबंटू 16 और 14 के लिए, पीपी से स्थापित करने से मुझे संस्करण 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

कोड नीचे बाहरी पुस्तकालयों के बिना मेरे लिए काम किया करते हैं। मैंने पायथन 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) 

और उपयोग, कुल, प्रयुक्त और नि: शुल्क राम

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 निर्भरता के साथ राम के उपयोग के लिए एक-लाइनर:

import os 
tot_m, used_m, free_m = map(int, os.popen('free -t -m').readlines()[-1].split()[1:]) 
संबंधित मुद्दे