天天看点

如何在Python中获得当前的CPU和RAM使用率?

本文翻译自:How to get current CPU and RAM usage in Python?

What's your preferred way of getting current system status (current CPU, RAM, free disk space, etc.) in Python?

在Python中获取当前系统状态(当前CPU,RAM,可用磁盘空间等)的首选方式是什么?

Bonus points for *nix and Windows platforms.

* nix和Windows平台的奖励积分。

There seems to be a few possible ways of extracting that from my search:

似乎有几种方法可以从我的搜索中提取出来:
  1. Using a library such as PSI (that currently seems not actively developed and not supported on multiple platform) or something like pystatgrab (again no activity since 2007 it seems and no support for Windows). 使用PSI之类的库(目前似乎尚未积极开发并且在多个平台上不受支持)或pystatgrab之类的库 (自2007年以来一直没有活动,它似乎也不支持Windows)。
  2. Using platform specific code such as using a

    os.popen("ps")

    or similar for the *nix systems and

    MEMORYSTATUS

    in

    ctypes.windll.kernel32

    (see this recipe on ActiveState ) for the Windows platform. 对于Windows平台,使用平台特定的代码,例如对* nix系统使用

    os.popen("ps")

    或类似代码,并在

    ctypes.windll.kernel32

    MEMORYSTATUS

    (请参见ActiveState上的此配方 )。
    One could put a Python class together with all those code snippets. 可以将Python类与所有这些代码段放在一起。

It's not that those methods are bad but is there already a well-supported, multi-platform way of doing the same thing?

并不是说这些方法不好,而是已经有一种受支持的,跨平台的方法来做同样的事情?

#1楼

参考:https://stackoom.com/question/19oS/如何在Python中获得当前的CPU和RAM使用率

#2楼

The psutil library will give you some system information (CPU / Memory usage) on a variety of platforms:

psutil库将为您提供各种平台上的一些系统信息(CPU /内存使用情况):
psutil is a module providing an interface for retrieving information on running processes and system utilization (CPU, memory) in a portable way by using Python, implementing many functionalities offered by tools like ps, top and Windows task manager. psutil是一个模块,提供了一个接口,该接口通过使用Python以可移植的方式检索有关正在运行的进程和系统利用率(CPU,内存)的信息,实现了ps,top和Windows任务管理器等工具提供的许多功能。 It currently supports Linux, Windows, OSX, Sun Solaris, FreeBSD, OpenBSD and NetBSD, both 32-bit and 64-bit architectures, with Python versions from 2.6 to 3.5 (users of Python 2.4 and 2.5 may use 2.1.3 version). 它目前支持32位和64位体系结构的Linux,Windows,OSX,Sun Solaris,FreeBSD,OpenBSD和NetBSD,Python版本从2.6到3.5(Python 2.4和2.5的用户可以使用2.1.3版本)。

UPDATE: Here is some example usages of

psutil

:

更新:这是

psutil

一些用法

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())
           

#3楼

I don't believe that there is a well-supported multi-platform library available.

我认为没有可用的受支持的多平台库。

Remember that Python itself is written in C so any library is simply going to make a smart decision about which OS-specific code snippet to run, as you suggested above.

请记住,Python本身是用C编写的,因此,任何一个库都只是要明智地决定要运行哪个特定于操作系统的代码段,如您在上面建议的那样。

#4楼

"... current system status (current CPU, RAM, free disk space, etc.)" And "*nix and Windows platforms" can be a difficult combination to achieve.

“ ...当前系统状态(当前CPU,RAM,可用磁盘空间等)”和“ * nix和Windows平台”可能很难组合。

The operating systems are fundamentally different in the way they manage these resources.

操作系统在管理这些资源的方式上根本不同。

Indeed, they differ in core concepts like defining what counts as system and what counts as application time.

实际上,它们在核心概念方面有所不同,例如定义什么才算是系统以及什么才算是应用程序时间。

"Free disk space"?

“可用磁盘空间”?

What counts as "disk space?"

什么算作“磁盘空间”?

All partitions of all devices?

所有设备的所有分区?

What about foreign partitions in a multi-boot environment?

多重引导环境中的外部分区呢?

I don't think there's a clear enough consensus between Windows and *nix that makes this possible.

我认为Windows和* nix之间没有足够清晰的共识使之成为可能。

Indeed, there may not even be any consensus between the various operating systems called Windows.

实际上,在称为Windows的各种操作系统之间甚至可能没有达成共识。

Is there a single Windows API that works for both XP and Vista?

是否有一个适用于XP和Vista的Windows API?

#5楼

Here's something I put together a while ago, it's windows only but may help you get part of what you need done.

这是我前几天整理的东西,仅是Windows,但可以帮助您获得部分所需的工作。

Derived from: "for sys available mem" http://msdn2.microsoft.com/en-us/library/aa455130.aspx

派生自:“ 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

“单个过程信息和python脚本示例” 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, then may want to investigate the WMI tools a vailable.

注意:WMI界面/过程也可用于执行类似的任务,因为当前的方法满足了我的需求,所以我在这里不使用它,但是如果有朝一日需要扩展或改进它,则可能需要研究可用的WMI工具。 。

WMI for python:

适用于python的WMI:

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

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

The code:

编码:
'''
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

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

#6楼

You can use psutil or psmem with subprocess example code

您可以将psutil或psmem与子流程示例代码一起使用
import subprocess
cmd =   subprocess.Popen(['sudo','./ps_mem'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) 
out,error = cmd.communicate() 
memory = out.splitlines()
           

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

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

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

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