做监控的时候,可能会用到psutil这个python包来获取机器的cpu、memory、disk、net、os和一些其他的信息,今天对psutil这个包做了进一步的分析。各项参数的获取大同小异,此处以memory为例。
获取psutil python包,github
https://github.com/giampaolo/psutil
此处指定获取相关信息的主目录,如:linux环境下,
psutil/init.py
if LINUX:
...
PROCFS_PATH = "/proc"
...
获取内存的信息,从如下代码可以看到内存信息的获取“/proc/meminfo”。
/psutil/_pslinux.py
def virtual_memory():
...
missing_fields = []
mems = {}
with open_binary('%s/meminfo' % get_procfs_path()) as f:
for line in f:
fields = line.split()
mems[fields[0]] = int(fields[1]) * 1024
total = mems[b'MemTotal:']
free = mems[b'MemFree:']
...
def swap_memory():
...
mems = {}
with open_binary('%s/meminfo' % get_procfs_path()) as f:
for line in f:
fields = line.split()
mems[fields[0]] = int(fields[1]) * 1024
try:
total = mems[b'SwapTotal:']
free = mems[b'SwapFree:']
...
used = total - free
percent = usage_percent(used, total, round_=1)
...
函数“open_binary”:
def open_binary(fname, **kwargs):
return open(fname, "rb", **kwargs)
官方文档:
https://psutil.readthedocs.io/en/latest/#
来源:oschina
链接:https://my.oschina.net/u/4504487/blog/4816464