كيفية الحصول على الاستخدام الحالي لوحدة المعالجة المركزية وذاكرة الوصول العشوائي في بيثون؟

StackOverflow https://stackoverflow.com/questions/276052

سؤال

ما هي الطريقة المفضلة لديك للحصول على حالة النظام الحالية (وحدة المعالجة المركزية الحالية، ذاكرة الوصول العشوائي، مساحة القرص الحرة، وما إلى ذلك) في بايثون؟نقاط إضافية لمنصات *nix وWindows.

يبدو أن هناك بعض الطرق الممكنة لاستخراج ذلك من بحثي:

  1. باستخدام مكتبة مثل رطل لكل بوصة مربعة (الذي يبدو حاليًا أنه لم يتم تطويره بشكل نشط وغير مدعوم على منصات متعددة) أو شيء من هذا القبيل com.pystatgrab (مرة أخرى لا يوجد نشاط منذ عام 2007 على ما يبدو ولا يوجد دعم لنظام التشغيل Windows).

  2. استخدام رمز خاص بالمنصة مثل استخدام a os.popen("ps") أو ما شابه ذلك بالنسبة لأنظمة *nix و MEMORYSTATUS في ctypes.windll.kernel32 (يرى هذه الوصفة على ActiveState) لنظام التشغيل Windows.يمكن للمرء أن يجمع فئة Python مع كل مقتطفات التعليمات البرمجية تلك.

لا يعني ذلك أن هذه الأساليب سيئة، ولكن هل توجد بالفعل طريقة مدعومة جيدًا ومتعددة المنصات للقيام بنفس الشيء؟

هل كانت مفيدة؟

المحلول

مكتبة بسوتيل سيعطيك بعض معلومات النظام (استخدام وحدة المعالجة المركزية / الذاكرة) على مجموعة متنوعة من الأنظمة الأساسية:

psutil عبارة عن وحدة توفر واجهة لاسترداد المعلومات حول العمليات الجارية واستخدام النظام (وحدة المعالجة المركزية والذاكرة) بطريقة محمولة باستخدام Python، وتنفيذ العديد من الوظائف التي توفرها أدوات مثل ps وtop وإدارة مهام Windows.

وهو يدعم حاليًا Linux، وWindows، وOSX، وSun Solaris، وFreeBSD، وOpenBSD، وNetBSD، وكلاهما معماريات 32 بت و64 بت، مع إصدارات Python من 2.6 إلى 3.5 (يمكن لمستخدمي Python 2.4 و2.5 استخدام الإصدار 2.1.3).


تحديث:فيما يلي بعض الأمثلة على استخدامات psutil:

#!/usr/bin/env python
import psutil
# gives a single float value
psutil.cpu_percent()
# gives an object with many fields
psutil.virtual_memory()
# you can convert that object to a dictionary 
dict(psutil.virtual_memory()._asdict())

نصائح أخرى

استخدم ال مكتبة بسوتيل.في Ubuntu 18.04، تم تثبيت النقطة 5.5.0 (أحدث إصدار) اعتبارًا من 30-1-2019.قد تتصرف الإصدارات الأقدم بشكل مختلف بعض الشيء.يمكنك التحقق من إصدار psutil الخاص بك عن طريق القيام بذلك في Python:

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

للحصول على بعض إحصائيات الذاكرة ووحدة المعالجة المركزية:

from __future__ import print_function
import psutil
print(psutil.cpu_percent())
print(psutil.virtual_memory())  # physical memory usage
print('memory % used:', psutil.virtual_memory()[2])

ال virtual_memory (tuple) سيكون له النسبة المئوية للذاكرة المستخدمة على مستوى النظام.يبدو أن هذا مبالغ فيه بنسبة قليلة بالنسبة لي على Ubuntu 18.04.

يمكنك أيضًا الحصول على الذاكرة التي يستخدمها مثيل Python الحالي:

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 لـ psutil.

فقط لنظام التشغيل Linux:بطانة واحدة لاستخدام ذاكرة الوصول العشوائي (RAM) مع تبعية stdlib فقط:

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

يحرر:تبعية نظام التشغيل للحل المحدد

أدناه الرموز، دون مكتبات خارجية عملت بالنسبة لي.لقد اختبرت في بيثون 2.7.9

استخدام المعالج

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'

إليك شيء قمت بتجميعه منذ فترة، وهو عبارة عن نوافذ فقط ولكنه قد يساعدك في إنجاز جزء مما تحتاج إلى إنجازه.

مستمدة من:"للذاكرة المتاحة للنظام"http://msdn2.microsoft.com/en-us/library/aa455130.aspx

"معلومات العملية الفردية وأمثلة نص بايثون"http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true

ملحوظة:تتوفر واجهة/عملية WMI أيضًا لأداء مهام مماثلة ، ولا أستخدمها هنا لأن الطريقة الحالية تغطي احتياجاتي ، ولكن إذا كانت هناك حاجة إليها في يوم من الأيام لتمديد هذا الأمر ، فقد ترغب في التحقيق في أدوات 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

"...حالة النظام الحالية (وحدة المعالجة المركزية الحالية، وذاكرة الوصول العشوائي، ومساحة القرص الحرة، وما إلى ذلك)" ويمكن أن يكون الجمع بين "*nix وWindows" مزيجًا صعب التحقيق.

تختلف أنظمة التشغيل بشكل أساسي في الطريقة التي تدير بها هذه الموارد.في الواقع، فهي تختلف في المفاهيم الأساسية مثل تحديد ما يعتبر نظامًا وما يعتبر وقت التطبيق.

"مساحة حرة"؟ما الذي يعتبر "مساحة القرص؟" جميع أقسام جميع الأجهزة؟ماذا عن الأقسام الخارجية في بيئة التشغيل المتعدد؟

لا أعتقد أن هناك إجماعًا واضحًا بدرجة كافية بين Windows و*nix يجعل هذا ممكنًا.في الواقع، قد لا يكون هناك أي توافق في الآراء بين أنظمة التشغيل المختلفة التي تسمى Windows.هل توجد واجهة برمجة تطبيقات Windows واحدة تعمل لكل من XP وVista؟

أشعر أن هذه الإجابات كانت مكتوبة لـ Python 2، وعلى أي حال لم يذكر أحد المعيار resource الحزمة المتوفرة لـ Python 3.ويوفر أوامر للحصول على المورد حدود لعملية معينة (عملية استدعاء بايثون بشكل افتراضي).هذا ليس هو نفسه الحصول على التيار الاستخدام من الموارد من قبل النظام ككل، ولكن يمكن أن يحل بعض المشاكل نفسها مثل على سبيل المثال."أريد التأكد من أنني أستخدم فقط X مقدارًا من ذاكرة الوصول العشوائي (RAM) مع هذا البرنامج النصي."

هذا البرنامج النصي لاستخدام وحدة المعالجة المركزية:

import os

def get_cpu_load():
    """ Returns a list CPU Loads"""
    result = []
    cmd = "WMIC CPU GET LoadPercentage "
    response = os.popen(cmd + ' 2>&1','r').read().strip().split("\r\n")
    for load in response[1:]:
       result.append(int(load))
    return result

if __name__ == '__main__':
    print get_cpu_load()

لقد اخترنا استخدام مصدر المعلومات المعتاد لهذا لأنه يمكننا العثور على تقلبات لحظية في الذاكرة الحرة وشعرنا بالاستعلام عن meminfo مصدر البيانات كان مفيدا.وقد ساعدنا هذا أيضًا في الحصول على عدد قليل من المعلمات ذات الصلة التي تم تحليلها مسبقًا.

شفرة

import os

linux_filepath = '/proc/meminfo'
meminfo = dict((i.split()[0].rstrip(':'), int(i.split()[1]))
               for i in open(linux_filepath).readlines())
meta['memory_total_gb'] = meminfo['MemTotal'] / (2**20)
meta['memory_free_gb'] = meminfo['MemFree'] / (2**20)
meta['memory_available_gb'] = meminfo['MemAvailable'] / (2**20)

الإخراج للرجوع إليها (قمنا بتجريد جميع الأسطر الجديدة لمزيد من التحليل)

إجمالي الذاكرة:1014500 كيلو بايت ميمفري:562680 كيلو بايت الذاكرةمتوفرة:646364 كيلو بايت مخازن المؤقتة:15144 كيلو بايت مخبأة:210720 كيلو بايت0 كيلو بايت نشط:261476 كيلو بايت غير نشط:128888 كيلو بايت نشط (مجهول):167092 كيلو بايت غير نشط (مجهول):20888 كيلو بايت نشط (ملف):94384 كيلو بايت غير نشط (ملف):108000 كيلو بايت لا يمكن التخلص منه:3652 كيلو بايت ملين:3652 كيلو بايت إجمالي المبادلة:0 كيلو بايت0 كيلو بايت القذرة:0 كيلو بايت0 كيلو بايت الصفحات المجهولة:168160 كيلو بايت المعينة:81352 كيلو بايت شميم:21060 كيلو بايت34492 كيلو بايت قابلة للإلغاء:18044 كيلو بايت SU16448 كيلو بايت2672 كيلو بايت pagetables:8180 كيلو بايت NFS_غير مستقر:0 كيلو بايت ترتد:0 كيلو بايت0 كيلو بايت الالتزام:507248 كيلوبايت ملتزم بها:1038756 كيلو بايت فمالوكالإجمالي:34359738367 كيلو بايت فمالوكالمستخدمة:0 كيلو بايت فمالوكتشنك:0 كيلو بايت0 كيلو بايت صفحات ضخمة:88064 كيلو بايت المجموع:0 كيلو بايت0 كيلو بايت ضخمة pages_total:0 صفحات ضخمة_مجانية:0 صفحات ضخمة_Rsvd:0 صفحات ضخمة_مفاجأة:0 حجم الصفحات ضخم:2048 كيلو بايت DirectMap4k:43008 كيلو بايت DirectMap2M:1005568 كيلو بايت

  • للحصول على تفاصيل وحدة المعالجة المركزية استخدم psutil مكتبة

    https://psutil.readthedocs.io/en/latest/#cpu

  • بالنسبة لتردد ذاكرة الوصول العشوائي (بالميغاهرتز)، استخدم مكتبة Linux المضمنة com.dmidecode والتلاعب في الإخراج قليلاً ؛).يحتاج هذا الأمر إلى إذن الجذر ومن ثم توفير كلمة المرور الخاصة بك أيضًا.فقط انسخ استبدال الثناء التالي com.mypass مع كلمة المرور الخاصة بك

import os

os.system("echo mypass | sudo -S dmidecode -t memory | grep 'Clock Speed' | cut -d ':' -f2")

------------------- انتاج ---------------------------
1600 طن متري/ثانية
مجهول
1600 طن متري/ثانية
غير معروف 0

  • بشكل أكثر تحديدا
    [i for i in os.popen("echo mypass | sudo -S dmidecode -t memory | grep 'Clock Speed' | cut -d ':' -f2").read().split(' ') if i.isdigit()]

-------------------------- انتاج ----------------------- --
['1600', '1600']

يمكنك استخدام Psutil أو PSMEM مع رمز مثال Subprocess

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

استنادًا إلى رمز استخدام وحدة المعالجة المركزية بواسطة @Hrabal، هذا ما أستخدمه:

from subprocess import Popen, PIPE

def get_cpu_usage():
    ''' Get CPU usage on Linux by reading /proc/stat '''

    sub = Popen(('grep', 'cpu', '/proc/stat'), stdout=PIPE, stderr=PIPE)
    top_vals = [int(val) for val in sub.communicate()[0].split('\n')[0].split[1:5]]

    return (top_vals[0] + top_vals[2]) * 100. /(top_vals[0] + top_vals[2] + top_vals[3])

لا أعتقد أن هناك مكتبة متعددة المنصات مدعومة جيدًا.تذكر أن Python نفسها مكتوبة بلغة C، لذا فإن أي مكتبة ستتخذ ببساطة قرارًا ذكيًا بشأن مقتطف التعليمات البرمجية الخاص بنظام التشغيل الذي سيتم تشغيله، كما اقترحت أعلاه.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top