Python에서 현재 CPU 및 RAM 사용량을 얻는 방법은 무엇입니까?
Python에서 현재 시스템 상태(현재 CPU, RAM, 빈 디스크 공간 등)를 어떻게 확인할 수 있습니까?Unix 플랫폼과 Windows 플랫폼 모두에서 동작하는 것이 이상적입니다.
검색에서 추출할 수 있는 몇 가지 방법이 있는 것 같습니다.
PSI 등의 라이브러리(현재는 적극적으로 개발되지 않아 여러 플랫폼에서 지원되지 않는 것으로 보인다) 또는 pystatgrab 등의 라이브러리 사용(2007년 이후 활동이 없으며 Windows를 지원하지 않는 것으로 보인다)
( 「」등 )
os.popen("ps")
*nix 시스템 및 이와 유사합니다.MEMORYSTATUS
ctypes.windll.kernel32
(ActiveState의 이 레시피를 참조해 주세요).Python 클래스와 코드 스니펫을 조합할 수 있습니다.
이러한 방법이 나쁜 것은 아니지만, 동일한 작업을 수행할 수 있는 잘 지원되는 멀티 플랫폼 방법이 이미 있습니까?
psutil 라이브러리는 다양한 플랫폼의 CPU, RAM 등에 대한 정보를 제공합니다.
psutil은 Python을 사용하여 실행 중인 프로세스와 시스템 사용률(CPU, 메모리)에 대한 정보를 포터블 방식으로 검색하는 인터페이스를 제공하는 모듈로 ps, top, Windows 태스크 매니저 등의 툴에서 제공되는 많은 기능을 구현합니다.
현재 Python 버전 2.6부터 3.5까지 Linux, Windows, OSX, Sun Solaris, FreeBSD, OpenBSD 및 NetBSD를 지원합니다(Python 2.4 및 2.5 사용자는 2.1.3 버전을 사용할 수 있음).
몇 가지 예:
#!/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())
# you can have the percentage of used RAM
psutil.virtual_memory().percent
79.2
# you can calculate percentage of available memory
psutil.virtual_memory().available * 100 / psutil.virtual_memory().total
20.8
다음은 더 많은 개념과 관심 개념을 제공하는 다른 문서입니다.
psutil 라이브러리를 사용합니다.Ubuntu 18.04에서 pip은 2019년 1월 30일 현재 5.5.0(최신 버전)을 설치했습니다.이전 버전은 다소 다르게 동작할 수 있습니다.Python에서 다음을 수행하여 psutil 버전을 확인할 수 있습니다.
from __future__ import print_function # for Python2
import psutil
print(psutil.__version__)
메모리 및 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()
python_process = psutil.Process(pid)
memoryUse = python_process.memory_info()[0]/2.**30 # memory use in GB...I think
print('memory use:', memoryUse)
Python 스크립트를 현재 메모리에 사용할 수 있습니다.
psutil의 pypi 페이지에 더 자세한 예가 있습니다.
Linux만 해당: stdlib 의존관계만 있는 RAM 사용량에 대한 단일 라인:
import os
tot_m, used_m, free_m = map(int, os.popen('free -t -m').readlines()[-1].split()[1:])
RAM을 조합하면 을 할 수.tqdm
★★★★★★★★★★★★★★★★★」psutil
가 높은 연산할 때 할 수 . 부하가 높은 연산/처리를 실행할 때 편리할 수 있습니다.
코드 변경 없이 주피터에서도 동작합니다.
from tqdm import tqdm
from time import sleep
import psutil
with tqdm(total=100, desc='cpu%', position=1) as cpubar, tqdm(total=100, desc='ram%', position=0) as rambar:
while True:
rambar.n=psutil.virtual_memory().percent
cpubar.n=psutil.cpu_percent()
rambar.refresh()
cpubar.refresh()
sleep(0.5)
멀티프로세싱 라이브러리를 사용하여 이러한 진행 표시줄을 별도의 프로세스에 배치하는 것이 편리합니다.
아래 코드는 외부 라이브러리 없이 작동했습니다.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("CPU Usage = " + CPU_Pct) # print results
또한 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'
프로그램의 라인별 메모리와 시간 분석을 얻으려면memory_profiler
★★★★★★★★★★★★★★★★★」line_profiler
.
설치:
# Time profiler
$ pip install line_profiler
# Memory profiler
$ pip install memory_profiler
# Install the dependency for a faster analysis
$ pip install psutil
공통적인 부분은 각 장식기를 사용하여 분석할 함수를 지정하는 것입니다.
: : 파일 Python에는 몇 .main.py
츠키노그 중 하나는linearRegressionfit()
@profile
가지 모두에 에 도움이 됩니다.시간과 메모리
함수 정의를 다음과 같이 변경합니다.
@profile
def linearRegressionfit(Xt,Yt,Xts,Yts):
lr=LinearRegression()
model=lr.fit(Xt,Yt)
predict=lr.predict(Xts)
# More Code
시간 프로파일링의 경우,
실행:
$ kernprof -l -v main.py
산출량
Total time: 0.181071 s
File: main.py
Function: linearRegressionfit at line 35
Line # Hits Time Per Hit % Time Line Contents
==============================================================
35 @profile
36 def linearRegressionfit(Xt,Yt,Xts,Yts):
37 1 52.0 52.0 0.1 lr=LinearRegression()
38 1 28942.0 28942.0 75.2 model=lr.fit(Xt,Yt)
39 1 1347.0 1347.0 3.5 predict=lr.predict(Xts)
40
41 1 4924.0 4924.0 12.8 print("train Accuracy",lr.score(Xt,Yt))
42 1 3242.0 3242.0 8.4 print("test Accuracy",lr.score(Xts,Yts))
메모리 프로파일링의 경우
실행:
$ python -m memory_profiler main.py
산출량
Filename: main.py
Line # Mem usage Increment Line Contents
================================================
35 125.992 MiB 125.992 MiB @profile
36 def linearRegressionfit(Xt,Yt,Xts,Yts):
37 125.992 MiB 0.000 MiB lr=LinearRegression()
38 130.547 MiB 4.555 MiB model=lr.fit(Xt,Yt)
39 130.547 MiB 0.000 MiB predict=lr.predict(Xts)
40
41 130.547 MiB 0.000 MiB print("train Accuracy",lr.score(Xt,Yt))
42 130.547 MiB 0.000 MiB print("test Accuracy",lr.score(Xts,Yts))
는, ,, 모, 음, 음, 음을 사용해 할 수도 .matplotlib
.
$ mprof run main.py
$ mprof plot
line_profiler
3.0 == 3.0.2bps
memory_profiler
0.0gc == 0.57.0gc
psutil
0420 == 5.7.0
편집: 프로파일러의 결과는 TAMPA 패키지를 사용하여 해석할 수 있습니다.이를 사용하면 다음과 같이 원하는 줄별 플롯을 얻을 수 있습니다.
빈 메모리에서 순간적인 변동을 발견할 수 있고 meminfo 데이터 소스를 조회하는 것이 도움이 된다고 생각했기 때문에 일반 정보 소스를 사용하는 것을 선택했습니다.이를 통해 사전 구문 분석된 몇 가지 관련 매개 변수를 더 얻을 수 있었습니다.
코드
import os
linux_filepath = "/proc/meminfo"
meminfo = dict(
(i.split()[0].rstrip(":"), int(i.split()[1]))
for i in open(linux_filepath).readlines()
)
meminfo["memory_total_gb"] = meminfo["MemTotal"] / (2 ** 20)
meminfo["memory_free_gb"] = meminfo["MemFree"] / (2 ** 20)
meminfo["memory_available_gb"] = meminfo["MemAvailable"] / (2 ** 20)
참조용 출력(추가 분석을 위해 모든 새 라인을 제거함)
MemTotal: 1014500kB MemFree: 562680kB MemAvailable: 646364kB 버퍼: 15144kB 캐시 완료: 210720kB 스왑 캐시 완료: 0kB 액티브: 261476kB 비액티브: 1288kB 액티브(an) 167092Kon(비액티브)AnonPages: 168160kB 매핑: 81352kB Shmem: 21060kB 슬래브: 34492kB SReclaimable: 18044kB Sunreclaim: 16448kB 커널스택: 2672kB 페이지 테이블: 8180kB NFS_unstable 0KB 바운스테이블: 0KBAS: 1038756kB Vmalloc합계: 34359738367kB VmallocUsed: 0kB VmallocChunk: 0kB 하드웨어 파손: 0kB AnonHugePages: 88064kB Cma합계: 0kB Cma_Free 0B 페이지: 0kB 대용량합계: 0 HergePages_Free: 0 HergePages_Rvd: 0 HergePages_Surp: 0 HergePages_Surp: 0 HergePages: 2048kB DirectMap4k: 43008kB DirectMap2M: 1005568kB
여기 제가 얼마 전에 정리한 것이 있습니다. 창문에 불과하지만 필요한 작업의 일부를 수행하는 데 도움이 될 수 있습니다.
출처: "for sys available mem" http://msdn2.microsoft.com/en-us/library/aa455130.aspx
"개별 프로세스 정보 및 python 스크립트 예제" http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true
메모: WMI 인터페이스/프로세스는 현재 방법은 제 요구를 커버하고 있기 때문에 여기서 사용하지 않는 유사한 태스크에도 사용할 수 있습니다.그러나 언젠가 이 확장이나 개선이 필요할 경우 사용 가능한 WMI 도구를 조사하는 것이 좋습니다.
python용 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
이 답변은 Python 2용으로 작성된 것 같습니다.어쨌든 Python 3에서 사용할 수 있는 표준 패키지에 대해서는 아무도 언급하지 않았습니다.이 명령어는 특정 프로세스의 리소스 제한(기본적으로 Python 프로세스 호출)을 얻기 위한 명령을 제공합니다.이는 시스템 전체의 현재 리소스 사용률을 얻는 것과는 다르지만 "이 스크립트에서 X개의 RAM만 사용하고 싶다"와 같은 문제를 해결할 수 있습니다.
은 모든 점들을 종합한 이다.psutil
+os
Unix windows Windows 、 음 unix unix unix unix 、 음음 unix unix unix unix unix unix 。이를 통해 다음과 같은 이점을 얻을 수 있습니다.
- CPU
- 기억
- 디스크
코드:
import os
import psutil # need: pip install psutil
In [32]: psutil.virtual_memory()
Out[32]: svmem(total=6247907328, available=2502328320, percent=59.9, used=3327135744, free=167067648, active=3671199744, inactive=1662668800, buffers=844783616, cached=1908920320, shared=123912192, slab=613048320)
In [33]: psutil.virtual_memory().percent
Out[33]: 60.0
In [34]: psutil.cpu_percent()
Out[34]: 5.5
In [35]: os.sep
Out[35]: '/'
In [36]: psutil.disk_usage(os.sep)
Out[36]: sdiskusage(total=50190790656, used=41343860736, free=6467502080, percent=86.5)
In [37]: psutil.disk_usage(os.sep).percent
Out[37]: 86.5
"...현재 시스템 상태(현재 CPU, RAM, 빈 디스크 용량 등)" 및 "*nix 및 Windows 플랫폼"은 달성하기 어려운 조합일 수 있습니다.
운영체제는 이들 자원을 관리하는 방식이 근본적으로 다릅니다.실제로 이들은 시스템으로 간주되는 것과 애플리케이션 시간으로 간주되는 것의 정의와 같은 핵심 개념이 다릅니다.
"사용 가능한 디스크 공간""디스크 공간"은 무엇입니까?모든 디바이스의 모든 파티션?멀티부트 환경의 외부 파티션은 어떻습니까?
Windows와 *nix 사이에 이를 가능하게 하는 명확한 합의가 있다고 생각하지 않습니다.사실, 윈도우라고 불리는 다양한 운영 체제들 사이에 어떠한 합의도 이루어지지 않을 수도 있다.XP와 Vista에서 모두 사용할 수 있는 단일 Windows API가 있습니까?
첫 번째 응답에서 피드백을 받아 작은 변경을 가했다.
#!/usr/bin/env python
#Execute commond on windows machine to install psutil>>>>python -m pip install psutil
import psutil
print (' ')
print ('----------------------CPU Information summary----------------------')
print (' ')
# gives a single float value
vcc=psutil.cpu_count()
print ('Total number of CPUs :',vcc)
vcpu=psutil.cpu_percent()
print ('Total CPUs utilized percentage :',vcpu,'%')
print (' ')
print ('----------------------RAM Information summary----------------------')
print (' ')
# you can convert that object to a dictionary
#print(dict(psutil.virtual_memory()._asdict()))
# gives an object with many fields
vvm=psutil.virtual_memory()
x=dict(psutil.virtual_memory()._asdict())
def forloop():
for i in x:
print (i,"--",x[i]/1024/1024/1024)#Output will be printed in GBs
forloop()
print (' ')
print ('----------------------RAM Utilization summary----------------------')
print (' ')
# you can have the percentage of used RAM
print('Percentage of used RAM :',psutil.virtual_memory().percent,'%')
#79.2
# you can calculate percentage of available memory
print('Percentage of available RAM :',psutil.virtual_memory().available * 100 / psutil.virtual_memory().total,'%')
#20.8
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()
CPU에 대한 자세한 내용은 psutil 라이브러리를 사용하십시오.
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']
/meminfo/meminfo를 읽으면 사용된 메모리를 얻을 수 있습니다.
file1 = open('/proc/meminfo', 'r')
for line in file1:
if 'MemTotal' in line:
x = line.split()
memTotal = int(x[1])
if 'Buffers' in line:
x = line.split()
buffers = int(x[1])
if 'Cached' in line and 'SwapCached' not in line:
x = line.split()
cached = int(x[1])
if 'MemFree' in line:
x = line.split()
memFree = int(x[1])
file1.close()
percentage_used = int ( ( memTotal - (buffers + cached + memFree) ) / memTotal * 100 )
print(percentage_used)
@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])
psutil 또는 psmem을 하위 프로세스 예제 코드와 함께 사용할 수 있습니다.
import subprocess
cmd = subprocess.Popen(['sudo','./ps_mem'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
out,error = cmd.communicate()
memory = out.splitlines()
언급
https://github.com/Leo-g/python-flask-cmd
crontab을 사용하여 실행해도 pid가 인쇄되지 않음
셋업:*/1 * * * * sh dog.sh
에 있어서의 이 행crontab -e
import os
import re
CUT_OFF = 90
def get_cpu_load():
cmd = "ps -Ao user,uid,comm,pid,pcpu --sort=-pcpu | head -n 2 | tail -1"
response = os.popen(cmd, 'r').read()
arr = re.findall(r'\S+', response)
print(arr)
needKill = float(arr[-1]) > CUT_OFF
if needKill:
r = os.popen(f"kill -9 {arr[-2]}")
print('kill:', r)
if __name__ == '__main__':
# Test CPU with
# $ stress --cpu 1
# crontab -e
# Every 1 min
# */1 * * * * sh dog.sh
# ctlr o, ctlr x
# crontab -l
print(get_cpu_load())
@CodeGench의 솔루션에는 셸아웃이 필요하지 않으므로 Linux와 Python의 표준 라이브러리를 가정하면 다음과 같습니다.
def cpu_load():
with open("/proc/stat", "r") as stat:
(key, user, nice, system, idle, _) = (stat.readline().split(None, 5))
assert key == "cpu", "'cpu ...' should be the first line in /proc/stat"
busy = int(user) + int(nice) + int(system)
return 100 * busy / (busy + int(idle))
잘 지원되는 멀티 플랫폼 라이브러리가 있다고는 생각하지 않습니다.Python 자체는 C로 작성되어 있기 때문에 어떤 라이브러리가 어떤 OS 고유의 코드 스니펫을 실행할지에 대해 현명한 결정을 내릴 수 있습니다.
언급URL : https://stackoverflow.com/questions/276052/how-to-get-current-cpu-and-ram-usage-in-python
'programing' 카테고리의 다른 글
C에서 Linux와 공유 메모리를 사용하는 방법 (0) | 2023.01.21 |
---|---|
PHP interafce mysql()은 동작하지 않지만 mysqli()는 동작합니다.왜일까요? (0) | 2023.01.21 |
라라벨:글로벌 어레이의 데이터와 상수를 저장할 수 있는 장소 (0) | 2023.01.21 |
mysql의 큰 테이블에서 랜덤 행의 빠른 선택 (0) | 2023.01.21 |
MySQL의 다중 컬럼인덱스 필드 순서가 중요합니까? (0) | 2023.01.21 |