Question

Quelle est votre méthode préférée pour obtenir l’état actuel du système (processeur, RAM, espace disque disponible, etc.) en Python? Points bonus pour les plates-formes * nix et Windows.

Il semble y avoir plusieurs façons de l'extraire de ma recherche:

  1. Utiliser une bibliothèque telle que PSI (qui semble actuellement non développée et non prise en charge sur plusieurs plates-formes) ou quelque chose comme pystatgrab (encore aucune activité depuis 2007, semble-t-il, et aucune prise en charge de Windows).

  2. Utilisation de code spécifique à la plate-forme, comme l'utilisation d'un os.popen ("ps") ou similaire pour les systèmes * nix et de MEMORYSTATUS dans ctypes.windll.kernel32 (voir cette recette sur ActiveState ) pour la plate-forme Windows. On pourrait mettre une classe Python avec tous ces extraits de code.

Ce n'est pas que ces méthodes soient mauvaises, mais existe-t-il déjà un moyen multi-plateforme bien supporté de faire la même chose?

Était-ce utile?

La solution

La bibliothèque psutil vous fournira des informations système (utilisation du processeur / de la mémoire) sur une variété de plates-formes:

  

psutil est un module fournissant une interface permettant de récupérer des informations sur les processus en cours et l'utilisation du système (CPU, mémoire) de manière portable en utilisant Python, en implémentant de nombreuses fonctionnalités offertes par des outils tels que ps, top et le gestionnaire de tâches Windows.

     

Il prend actuellement en charge les architectures 32 bits et 64 bits sous Linux, Windows, OSX, Sun Solaris, FreeBSD, OpenBSD et NetBSD, avec les versions Python de la version 2.6 à la version 3.5 (les utilisateurs de Python 2.4 et 2.5 peuvent utiliser la version 2.1.3). version).

UPDATE: Voici quelques exemples d'utilisation de 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())

Autres conseils

Utilisez la bibliothèque psutil . Sur Ubuntu 18.04, pip installé 5.5.0 (dernière version) à compter du 30/01/2019. Les anciennes versions peuvent se comporter de manière quelque peu différente.  Vous pouvez vérifier votre version de psutil en procédant ainsi dans Python:

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

Pour obtenir des statistiques sur la mémoire et le processeur:

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

Le virtual_memory (tuple) aura le pourcentage de mémoire utilisé par l’ensemble du système. Cela semblait être surestimé de quelques pour cent pour moi sur Ubuntu 18.04.

Vous pouvez également obtenir la mémoire utilisée par l'instance Python actuelle:

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)

qui donne l'utilisation actuelle de la mémoire de votre script Python.

La page pypi pour psutil contient des exemples plus détaillés.

Seulement pour Linux: One-liner pour l'utilisation de la RAM avec uniquement la dépendance stdlib:

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

modifier: dépendance du système d'exploitation de la solution spécifiée

Les codes ci-dessous, sans bibliothèques externes, ont fonctionné pour moi. J'ai testé à Python 2.7.9

Utilisation de l'UC

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)

Et l'utilisation du bélier, totale, utilisée et gratuite

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'

Voici quelque chose que j'ai mis en place il y a quelque temps: il s'agit uniquement de Windows, mais peut vous aider à obtenir une partie de ce que vous devez faire.

dérivé de: " pour le système disponible mem " http://msdn2.microsoft.com/en-us/library/aa455130.aspx

"Exemples d'informations de processus et de scripts python individuels" http://www.microsoft.com/technet/scriptcenter/scripts /default.mspx?mfr=true

REMARQUE: l'interface / processus WMI est également disponible pour effectuer des tâches similaires.         Je ne l'utilise pas ici car la méthode actuelle couvre mes besoins, mais si un jour il est nécessaire de l'étendre ou de l'améliorer, alors vous voudrez peut-être examiner les outils WMI disponibles.

WMI pour python:

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

Le 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

"... état actuel du système (unité centrale, mémoire vive, espace disque disponible, etc.)" Et "* nix et Windows" " peut être une combinaison difficile à réaliser.

Les systèmes d’exploitation sont fondamentalement différents en ce qui concerne la gestion de ces ressources. En effet, ils diffèrent par des concepts de base tels que définir ce qui compte comme système et ce qui compte comme temps d’application.

"Espace disque libre" Qu'est-ce qui compte comme " espace disque? & Quot; Toutes les partitions de tous les appareils? Qu'en est-il des partitions étrangères dans un environnement à démarrage multiple?

Je ne pense pas qu'il existe un consensus suffisamment clair entre Windows et * nix pour que cela soit possible. En effet, il peut ne pas y avoir de consensus entre les différents systèmes d'exploitation appelés Windows. Existe-t-il une seule API Windows qui fonctionne à la fois pour XP et Vista?

J'ai l'impression que ces réponses ont été écrites pour Python 2 et que, de toute façon, personne n'a fait mention du standard ressource disponible pour Python 3. Il fournit des commandes permettant d'obtenir la ressource limits d'un processus donné (le processus Python appelant par défaut). . Ce n’est pas la même chose que d’obtenir l’utilisation actuelle des ressources par le système dans son ensemble, mais cela pourrait résoudre certains des mêmes problèmes, comme par exemple. "Je veux m'assurer que je n'utilise que X beaucoup de RAM avec ce script."

Ce script d'utilisation du processeur:

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

Nous avons choisi d'utiliser la source d'informations habituelle à cet effet car nous pouvions détecter des fluctuations instantanées de la mémoire disponible. Nous avons donc pensé qu'il était utile d'interroger la source de données meminfo . Cela nous a également permis d’obtenir quelques autres paramètres connexes pré-analysés.

Code

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)

Sortie pour référence (nous avons supprimé toutes les nouvelles lignes pour une analyse plus approfondie)

  

MemTotal: 1014500 kB MemFree: 562680 kB MemAvailable: 646364 kB   Tampons: 15144 kB En cache: 210720 kB Échanges en cache: 0 kB Actifs: 261476 kB   Inactif: 128888 kB Actif (anon): 167092 kB Inactif (anon): 20888 kB   Actif (fichier): 94384 ko Inactif (fichier): 108000 ko Imprévisible: 3652 ko   Verrouillé: 3652 ko SwapTotal: 0 ko Swap gratuit: 0 ko Sale: 0 ko Writeback:   0 kB AnonPages: 168160 kB Mappé: 81352 kB Shmem: 21060 kB Dalle: 34492   Ko. Récupérable: 18044 Ko. Récupération: 16448 Ko. Empilement de noyau: 2672 Ko.   Pages de page: 8180 ko NFS_Unstable: 0 ko Rebond: 0 ko WritebackTmp: 0 ko   CommitLimit: 507248 kB Committed_AS: 1038756 kB VmallocTotal:   34359738367 kB VmallocUtilisé: 0 kB VmallocChunk: 0 kB HardwareCorrupted:   0 kB AnonHugePages: 88064 kB CmaTotal: 0 kB CmaFree: 0 kB   HugePages_Total: 0 HugePages_Free: 0 HugePages_Rsvd: 0 HugePages_Surp:   0 Énormes pages: 2048 ko DirectMap4k: 43008 ko DirectMap2M: 1005568 ko

  • Pour les détails de la CPU, utilisez la psutil bibliothèque

    .
      

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

  • Pour la fréquence RAM (en MHz), utilisez la bibliothèque intégrée dmidecode de Linux et manipulez un peu la sortie;). cette commande nécessite une autorisation root, donc indiquez également votre mot de passe. copiez simplement la recommandation suivante en remplaçant mypass par votre mot de passe

  

import os

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

     

------------------- Sortie ---------------------------
  1600 MT / s
  Inconnu
  1600 MT / s
  Inconnu 0

  • plus précisément
    [i for i in os.popen ("echo mypass | sudo -S dmidecode -t memory | grep 'Horloge' | cut -d ':' -f2"). read (). split ('' ) si i.isdigit ()]
  

-------------------------- résultat -------------------- -----
  ['1600', '1600']

Vous pouvez utiliser psutil ou psmem avec un sous-processus exemple de code

import subprocess
cmd =   subprocess.Popen(['sudo','./ps_mem'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) 
out,error = cmd.communicate() 
memory = out.splitlines()

Référence http: // techarena51.com/index.php/how-to-install-python-3-and-flask-on-linux/

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

D'après le code d'utilisation du processeur de @Hrabal, voici ce que j'utilise:

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

Je ne pense pas qu'il existe une bibliothèque multi-plateformes bien supportée disponible. Rappelez-vous que Python lui-même est écrit en C, de sorte que toute bibliothèque va simplement prendre une décision éclairée en ce qui concerne le fragment de code spécifique au système d'exploitation à exécuter, comme vous l'avez suggéré ci-dessus.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top