用python获取系统状态

用python获取系统状态,python,operating-system,Python,Operating System,是否有任何方法可以在python中获取系统状态,例如可用内存量、正在运行的进程、cpu负载等。 我知道在linux上,我可以从/proc目录获得这个,但我也希望在unix和windows上这样做。我认为还没有跨平台的库(当然应该有一个) 但是,我可以向您提供一个片段,用于在Linux下从/proc/stat获取当前CPU负载: 编辑:将可怕的未文档化代码替换为略具python风格和文档化的代码 import time INTERVAL = 0.1 def getTimeList():

是否有任何方法可以在python中获取系统状态,例如可用内存量、正在运行的进程、cpu负载等。
我知道在linux上,我可以从/proc目录获得这个,但我也希望在unix和windows上这样做。

我认为还没有跨平台的库(当然应该有一个)

但是,我可以向您提供一个片段,用于在Linux下从
/proc/stat
获取当前CPU负载:

编辑:将可怕的未文档化代码替换为略具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)

我不知道目前有任何这样的库/包同时支持Linux和Windows。还有一个似乎不是很活跃的开发(尽管它已经支持各种各样的Unix平台),还有一个非常活跃的开发,可以在AIX、Linux、SunOS和Darwin上运行。这两个项目的目标都是在将来的某个时候提供Windows支持。祝你好运。

重复这些问题: