2009-08-18 52 views
10

有什麼辦法可以在python中獲得系統狀態,例如內存空間量,正在運行的進程,cpu負載等等。 我知道在Linux上我可以從/ proc目錄得到這個,但我想在unix和windows上做到這一點。在python中獲取系統狀態

+2

重複這些問題: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 – 2009-08-18 22:41:09

回答

8

我不知道任何這樣的庫/包目前支持Linux和Windows。有libstatgrab這似乎不是非常積極的開發(它已經支持各種各樣的Unix平臺,但非常活躍的PSI (Python System Information))在AIX,Linux,SunOS和達爾文工作。這兩個項目的目標都是在未來某個時候支持Windows。祝你好運。

7

我不認爲這是應該是一個跨平臺的庫,但(那裏,這絕對是一個雖然)

我不過爲您提供一個片段我用來從/proc/stat在當前CPU的負載Linux操作系統:

編輯:更換可怕的無證代碼稍微更Python和記錄代碼

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) – 2011-10-01 11:13:37