문제

Python에서 현재 시스템 상태(현재 CPU, RAM, 여유 디스크 공간 등)를 얻는 데 선호하는 방법은 무엇입니까?*nix 및 Windows 플랫폼에 대한 보너스 포인트.

내 검색에서 이를 추출하는 몇 가지 가능한 방법이 있는 것 같습니다.

  1. 다음과 같은 라이브러리를 사용하여 PSI (현재 적극적으로 개발되지 않았으며 여러 플랫폼에서 지원되지 않는 것 같습니다) 또는 이와 유사한 것 pystatgrab (2007년 이후에는 활동이 없는 것으로 보이며 Windows에 대한 지원도 없는 것 같습니다).

  2. 플랫폼별 코드 사용(예: os.popen("ps") 또는 *nix 시스템과 유사하며 MEMORYSTATUS ~에 ctypes.windll.kernel32 (보다 ActiveState의 이 레시피) Windows 플랫폼의 경우.모든 코드 조각과 함께 Python 클래스를 넣을 수 있습니다.

이러한 방법이 나쁘다는 것은 아니지만 동일한 작업을 수행하는 잘 지원되는 다중 플랫폼 방법이 이미 있습니까?

도움이 되었습니까?

해결책

Psutil 도서관 다양한 플랫폼에서 시스템 정보 (CPU / 메모리 사용량)를 제공합니다.

PSUTIL은 Python을 사용하여 휴대용 방식으로 실행 프로세스 및 시스템 활용 (CPU, 메모리)에 대한 정보를 검색하기위한 인터페이스를 제공하는 모듈이며 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())

다른 팁

사용 psutil 라이브러리.Ubuntu 18.04에서 pip는 2019년 1월 30일 현재 5.5.0(최신 버전)을 설치했습니다.이전 버전에서는 다소 다르게 동작할 수 있습니다.Python에서 다음을 수행하여 psutil 버전을 확인할 수 있습니다.

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

메모리 및 CPU 통계를 얻으려면:

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 (튜플)은 시스템 전체에서 사용되는 메모리 비율을 갖습니다.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 스크립트의 현재 메모리 사용량을 제공합니다.

에 대한 좀 더 자세한 예가 있습니다. psutil용 pypi 페이지.

Linux의 경우에만 : STDLIB 의존성 만있는 RAM 사용을위한 1 라이너 :

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

편집 : 지정된 솔루션 OS 종속성

아래 코드는 외부 라이브러리가없는 코드가 저를 위해 일했습니다. 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'

여기에 제가 한동안 함께 한 것이 있습니다. 창문 일 뿐이지 만 필요한 일의 일부를 얻는 데 도움이 될 수 있습니다.

파생 : "SYS 사용 가능한 MEM"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

"... 현재 시스템 상태 (현재 CPU, RAM, 무료 디스크 공간 등)"및 "*NIX 및 Windows 플랫폼"은 달성하기 어려운 조합이 될 수 있습니다.

운영 체제는 이러한 리소스를 관리하는 방식이 근본적으로 다릅니다. 실제로, 그들은 시스템으로 간주되는 것을 정의하는 것과 응용 프로그램 시간으로 간주되는 것과 같은 핵심 개념이 다릅니다.

"무료 디스크 공간"? "디스크 공간"으로 간주되는 것은 무엇입니까? 모든 장치의 모든 파티션? 다중 부팅 환경에서 외국 파티션은 어떻습니까?

나는 이것을 가능하게하는 Windows와 *nix 사이에 충분한 합의가 있다고 생각하지 않습니다. 실제로, Windows라는 다양한 운영 체제 사이에는 어떤 합의도 없을 수도 있습니다. XP와 Vista 모두에 적합한 단일 Windows API가 있습니까?

나는이 답변이 Python 2를 위해 작성된 것처럼 느껴지고 어쨌든 아무도 표준에 대해 언급하지 않았습니다. resource Python 3에 사용할 수있는 패키지 3. 리소스를 얻기위한 명령을 제공합니다. 제한 주어진 프로세스 (기본적으로 호출 파이썬 프로세스). 이것은 전류를 얻는 것과 동일하지 않습니다 용법 시스템 전체의 리소스이지만 "이 스크립트와 함께 x 많은 RAM 만 사용하고 싶습니다"와 같은 동일한 문제를 해결할 수 있습니다.

CPU 사용을위한이 스크립트 :

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)

참조를위한 출력 (우리는 추가 분석을 위해 모든 Newlines를 제거했습니다)

Memtotal : 1014500 KB Memfree : 562680 KB Memavailable : 646364 KB 버퍼 : 15144 KB 캐시드 : 210720 KB 스왑 캐시 : 0 KB 활성 : 261476 KB 비활성 : 12888 KB 활성 (ANON) : 167092 KB inactive (anon) : 20888KB active (anon) : 20888KB : 94384 kb 비활성 (파일) : 108000 KB는 평가할 수 없음 : 3652 KB mlocked : 3652 kb swaptotal : 0 KB swapfree : 0 KB Dirty : 0 KB Writ SrecLaimable : 18044 KB Sunreclaim : 16448 KB Kernelstack : 2672 KB Pagetables : 8180 KB NFS_UNSTABLE : 0 KB BOUNCE : 0 KB WRITE BBACKTMP : 0 KB CommitLimit : 507248 KB Committed_AS : 1038756 KB VMALLOCTOOTAL : 34359383. 0 KB AnonhugePages : 88064 KB CMATOTAL : 0 KB CMAFREE : 0 KB MUGEPAGES_TOTAL : 0 MAGENPAGES_FREE : 0 MAGENPAGES_RSVD : 0 MAGENPAGES_SURP : 0 MUGEPAGESIZE : 2048 KB DIRECTMAP4K : 43008 KB DIRECTMAP2M : 1005568 KB BB

  • CPU 세부 정보는 사용됩니다 psutil 도서관

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

  • RAM 주파수 (MHZ)의 경우 내장 된 Linux 라이브러리를 사용하십시오. dmidecode 출력을 조금 조작합니다.). 이 명령에는 루트 권한이 필요하므로 비밀번호도 제공합니다. 다음을 칭찬하는 것만 복사하십시오 mypass 비밀번호로

import os

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

-----------------------------------------------------
1600 mt/s
알려지지 않은
1600 mt/s
알 수없는 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을 사용할 수 있습니다.

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-ninux/

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

@hrabal의 CPU 사용 코드를 기반으로하는 것은 다음과 같습니다.

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로 작성되므로 모든 라이브러리는 위에서 제안한 것처럼 어떤 OS 특이 적 코드 스 니펫을 실행 해야하는지에 대한 현명한 결정을 내릴 것입니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top