2009-08-18 32 views
10

C'è un modo per ottenere lo stato del sistema in python, ad esempio la quantità di memoria libera, i processi in esecuzione, il carico della CPU e così via. So su linux. Posso ottenere questo dalla directory/proc, ma mi piacerebbe farlo anche su unix e windows.Ottenere lo stato del sistema in python

+2

duplicati di queste domande: http://stackoverflow.com/questions/276052/how-to-get-current-cpu-and-ram-usage- in-python http://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python/467291 –

risposta

8

non so di qualsiasi libreria/pacchetto che attualmente supporta sia Linux che Windows. C'è lo libstatgrab che non sembra essere molto sviluppato (supporta già una discreta varietà di piattaforme Unix) e il molto attivo PSI (Python System Information) che funziona su AIX, Linux, SunOS e Darwin. Entrambi i progetti mirano ad avere il supporto di Windows in futuro. In bocca al lupo.

7

Io non credo che ci sia una libreria multipiattaforma per quello ancora (ci sicuramente dovrebbe essere uno però)

Posso tuttavia offrire un frammento ho usato per ottenere il carico della CPU corrente /proc/stat sotto Linux:

Edit: sostituito il codice non documentata orribile con il codice di un po 'più divinatorio e documentato

import time 

INTERVAL = 0.1 

def getTimeList(): 
    """ 
    Fetches a list of time units the cpu has spent in various modes 
    Detailed explanation at http://www.linuxhowtos.org/System/procstat.htm 
    """ 
    cpuStats = file("/proc/stat", "r").readline() 
    columns = cpuStats.replace("cpu", "").split(" ") 
    return map(int, filter(None, columns)) 

def deltaTime(interval): 
    """ 
    Returns the difference of the cpu statistics returned by getTimeList 
    that occurred in the given time delta 
    """ 
    timeList1 = getTimeList() 
    time.sleep(interval) 
    timeList2 = getTimeList() 
    return [(t2-t1) for t1, t2 in zip(timeList1, timeList2)] 

def getCpuLoad(): 
    """ 
    Returns the cpu load as a value from the interval [0.0, 1.0] 
    """ 
    dt = list(deltaTime(INTERVAL)) 
    idle_time = float(dt[3]) 
    total_time = sum(dt) 
    load = 1-(idle_time/total_time) 
    return load 


while True: 
    print "CPU usage=%.2f%%" % (getCpuLoad()*100.0) 
    time.sleep(0.1) 
+5

[os.getloadavg()] (http://docs.python.org /library/os.html#os.getloadavg) –

Problemi correlati