有没有办法在python中获取系统状态,例如可用内存量,正在运行的进程,cpu加载等等。我知道在linux上我可以从/ proc目录中获取它,但我想在unix和windows上也这样做。
我不知道目前支持Linux和Windows的任何此类库/包。有libstatgrab似乎没有非常积极地开发(它已经支持了各种各样的Unix平台)和非常活跃的PSI (Python System Information),可以在AIX,Linux,SunOS和Darwin上运行。这两个项目都旨在将来某个时候提供Windows支持。祝好运。
我认为还没有一个跨平台的库(肯定应该有一个)
但是,我可以为您提供一个代码片段,用于从Linux下的/proc/stat
获取当前的CPU负载:
编辑:用稍微更加pythonic和文档代码替换可怕的未记录代码
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)
https://pypi.python.org/pypi/psutil
import psutil
psutil.get_pid_list()
psutil.virtual_memory()
psutil.cpu_times()
等等