2009-08-18 54 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