¿Cómo obtener el uso actual de CPU y RAM en Python?
¿Cuál es su forma preferida de obtener el estado actual del sistema (CPU actual, RAM, espacio libre en disco, etc.) en Python? Puntos de bonificación para las plataformas * nix y Windows.
Parece que hay algunas formas posibles de extraer eso de mi búsqueda:
Usando una biblioteca como PSI (que actualmente no parece desarrollada activamente y no es compatible con múltiples plataformas) o algo como pystatgrab (nuevamente no hay actividad desde 2007 parece y no hay soporte para Windows).
Usar código específico de la plataforma, como usar un
os.popen("ps")
o similar para los sistemas *nix yMEMORYSTATUS
enctypes.windll.kernel32
(ver esta receta en ActiveState) para la plataforma Windows. Uno podría poner una clase Python junto con todos esos fragmentos de código.
No es que esos métodos sean malos, pero ¿existe ya una forma multiplataforma bien apoyada de hacer lo mismo?
11 answers
La biblioteca psutil le dará cierta información del sistema (uso de CPU / Memoria) en una variedad de plataformas:
Psutil es un módulo que proporciona una interfaz para recuperar información sobre los procesos en ejecución y la utilización del sistema (CPU, memoria) de una manera portátil utilizando Python, implementando muchas funcionalidades ofrecidas por herramientas como ps, top y Windows task manager.
Actualmente soporta Linux, Windows, OSX, Sun Solaris, FreeBSD, OpenBSD y NetBSD, ambos arquitecturas de 32 bits y 64 bits, con versiones de Python de 2.6 a 3.5 (los usuarios de Python 2.4 y 2.5 pueden usar la versión 2.1.3).
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-10 14:12:26
Utilice la biblioteca psutil. Para mí en Ubuntu, pip instalado 0.4.3. Puedes comprobar tu versión de psutil haciendo esto en Python:
from __future__ import print_function
import psutil
print(psutil.__version__)
Para obtener algunas estadísticas de memoria y CPU:
from __future__ import print_function
import psutil
print(psutil.cpu_percent())
print(psutil.virtual_memory()) # physical memory usage
También me gusta hacer esto:
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)
Que da el uso actual de la memoria de su script Python.
Hay algunos ejemplos más detallados en la página pypi de para 4.3.0 y 0.5.0.
Para Ubuntu 16 y 14, la instalación desde pip me dio la versión 4.3.0, que no tiene el método phymem_usage (). Para obtener 0.5.0, puede hacer pip install psutil==0.5.0
, o descargar el tar.archivo gz , luego haga
tar -xvzf psutil-0.5.0.tar.gz
cd psutil-0.5.0
sudo python setup.py install
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-05 00:38:01
Por debajo de los códigos, sin bibliotecas externas funcionó para mí. Probé en Python 2.7.9
Uso de 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)
Y Uso de Ram, Total, Usado y Libre
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'
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-06 18:44:58
Un liner para el uso de RAM con solo dependencia stdlib:
import os
tot_m, used_m, free_m = map(int, os.popen('free -t -m').readlines()[-1].split()[1:])
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-16 13:24:10
Aquí hay algo que armé hace un tiempo, es solo Windows, pero puede ayudarlo a obtener parte de lo que necesita hacer.
Derivado de: "para los miembros disponibles de sys" http://msdn2.microsoft.com/en-us/library/aa455130.aspx
" información de procesos individuales y ejemplos de scripts python" http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true
NOTA: la interfaz/proceso WMI también está disponible para realizar tareas similares No lo soy. usándolo aquí porque el método actual cubre mis necesidades, pero si algún día es necesario ampliar o mejorar esto, entonces puede querer investigar las herramientas de WMI a vailable.
WMI para python:
Http://tgolden.sc.sabren.com/python/wmi.html
El código:
'''
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-22 01:11:50
"... estado actual del sistema (CPU actual, RAM, espacio libre en disco, etc.) "Y" * plataformas nix y Windows " pueden ser una combinación difícil de lograr.
Los sistemas operativos son fundamentalmente diferentes en la forma en que administran estos recursos. De hecho, difieren en conceptos básicos como definir lo que cuenta como sistema y lo que cuenta como tiempo de aplicación.
¿"Espacio libre en disco"? ¿Qué cuenta como "espacio en disco"?"Todas las particiones de todos los dispositivos? ¿Qué pasa con las particiones extranjeras en un ¿entorno multi-boot?
No creo que haya un consenso lo suficientemente claro entre Windows y *nix que haga esto posible. De hecho, puede que ni siquiera haya consenso entre los diversos sistemas operativos llamados Windows. ¿Hay una sola API de Windows que funcione tanto para XP como para Vista?
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-11-09 18:50:34
Siento que estas respuestas fueron escritas para Python 2, y en cualquier caso nadie ha hecho mención de la norma resource
paquete disponible para Python 3. Proporciona comandos para obtener el recurso limits de un proceso dado (el proceso que llama a Python por defecto). Esto no es lo mismo que obtener el uso actual de recursos por el sistema en su conjunto, pero podría resolver algunos de los mismos problemas como por ejemplo: "Quiero asegurarme de que solo uso X mucha RAM con este guión."
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-24 17:43:01
Puede usar psutil o psmem con subproceso código de ejemplo
import subprocess
cmd = subprocess.Popen(['sudo','./ps_mem'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
out,error = cmd.communicate()
memory = out.splitlines()
Referencia http://techarena51.com/index.php/how-to-install-python-3-and-flask-on-linux/
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-31 14:57:48
Elegimos usar la fuente de información habitual para esto porque pudimos encontrar fluctuaciones instantáneas en la memoria libre y sentimos que consultar la fuente de datos meminfo fue útil. Esto también nos ayudó a obtener algunos parámetros relacionados más que fueron pre-analizados.
Código
import os
....
memory_usage = os.popen("cat /proc/meminfo").read()
Salida para referencia (eliminamos todas las líneas nuevas para un análisis posterior)
MemTotal: 1014500 kB MemFree: 562680 kB MemAvailable: 646364 kB Buffers: 15144 kB Cached: 210720 kB SwapCached: 0 kB Active: 261476 kB Inactivo: 128888 kB Activo (anon): 167092 kB Inactivo(anon): 20888 kB Activo(archivo): 94384 kB Inactivo(archivo): 108000 kB Unevictable: 3652 kB Mlocked: 3652 kB SwapTotal: 0 kB SwapFree: 0 kB Dirty: 0 kB Writeback: 0 KB AnonPages: 168160 kB Mapped: 81352 kB Shmem: 21060 kB Slab: 34492 kB SReclaimable: 18044 kB SUnreclaim: 16448 kB KernelStack: 2672 kB PageTables: 8180 kB NFS_Unstable: 0 kB Bounce: 0 kB WritebackTmp: 0 kB Límite de compromiso: 507248 kB Committed_AS: 1038756 Kb VmallocTotal: 34359738367 kB VmallocUsed: 0 kB VmallocChunk: 0 kB HardwareCorrupted: 0 KB Anonhugepáginas: 88064 kB CmaTotal: 0 kB CmaFree: 0 kB HugePages_Total: 0 HugePages_Free: 0 HugePages_Rsvd: 0 HugePages_Surp: 0 Tamaño de la página: 2048 kB DirectMap4k: 43008 kB DirectMap2M: 1005568 kB
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-29 15:30:44
Este script para el uso de la 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()
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-01 07:06:46
No creo que haya una biblioteca multiplataforma bien soportada disponible. Recuerde que Python está escrito en C, por lo que cualquier biblioteca simplemente tomará una decisión inteligente sobre qué fragmento de código específico del sistema operativo ejecutar, como sugirió anteriormente.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-11-09 17:25:10