python 在python中获取系统状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1296703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting system status in python
提问by Botto
Is there any way to get system status in python, for example the amount of memory free, processes that are running, cpu load and so on. I know on linux I can get this from the /proc directory, but I would like to do this on unix and windows as well.
有没有办法在python中获取系统状态,例如可用内存量、正在运行的进程、cpu负载等。我知道在 linux 上我可以从 /proc 目录中得到它,但我也想在 unix 和 windows 上这样做。
采纳答案by Gerald Senarclens de Grancy
I don't know of any such library/ package that currently supports both Linux and Windows. There's libstatgrabwhich doesn't seem to be very actively developed (it already supports a decent variety of Unix platforms though) and the very active PSI (Python System Information)which works on AIX, Linux, SunOS and Darwin. Both projects aim at having Windows support sometime in the future. Good luck.
我不知道目前支持 Linux 和 Windows 的任何此类库/包。有libstatgrab似乎没有得到非常积极的开发(尽管它已经支持了相当多的 Unix 平台)和非常活跃的PSI(Python 系统信息),它适用于 AIX、Linux、SunOS 和 Darwin。这两个项目都旨在在未来某个时候获得 Windows 支持。祝你好运。
回答by OJW
https://pypi.python.org/pypi/psutil
https://pypi.python.org/pypi/psutil
import psutil
psutil.get_pid_list()
psutil.virtual_memory()
psutil.cpu_times()
etc.
等等。
回答by Otto Allmendinger
I don't think there is a cross-platform library for that yet (there definitely should be one though)
我认为还没有一个跨平台的库(尽管肯定应该有一个)
I can however provide you with one snippet I used to get the current CPU load from /proc/stat
under Linux:
但是,我可以为您提供一个我用来从/proc/stat
Linux 下获取当前 CPU 负载的片段:
Edit: replaced horrible undocumented code with slightly more pythonic and documented code
编辑:用稍微多一点的 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)