设为首页 加入收藏

TOP

使用Python统计Linux系统内存
2017-06-04 10:22:34 】 浏览:10086
Tags:使用 Python 统计 Linux 系统 内存

使用Python统计Linux系统内存,比较简单,支持-m -g -k选项。


#!/usr/bin/python
#*-*coding:utf8*-*
 
"""适用于在/proc/meminfo中提供了可用内存MemAvailable的系统使用"""
 
from optparse import OptionParser
import sys
 
parser = OptionParser()
parser.add_option("-k",
                        dest="k",
                        action="store_true",
                        default=True,
                        help="Display Meminfo KB")
parser.add_option("-m",
                        dest="m",
                        action="store_true",
                        default=False,
                        help="Display Meminfo MB")
parser.add_option("-g",
                        dest="g",
                        action="store_true",
                        default=False,
                        help="Display Meminfo GB")
 
option, args = parser.parse_args()
 
with open("/proc/meminfo") as meminfo:
    for i in meminfo:
        if i.startswith("MemTotal"):
            total_mem = i.split()
            total_mem = total_mem[1]
            continue
        elif i.startswith("MemAvailable"):
            free_mem = i.split()
            free_mem = free_mem[1]
            break
        else:
            pass
 
total_mem, free_mem = float(total_mem), float(free_mem)
 
x = free_mem/total_mem
 
if option.k and (not option.m) and (not option.g):
    print("总内存为:%d" %total_mem + " kB")
    print("剩余可用内存为:%d" %free_mem + " kB")
    print("剩余内存可用比例为:%d" %(x*100) + "%" )
elif option.k and option.m and (not option.g):
    print("总内存为:%d" %(total_mem/1024) + " MB")
    print("剩余可用内存为:%d" %(free_mem/1024) + " MB")
    print("剩余内存可用比例为:%d" %(x*100) + "%" )
elif option.k and (not option.m) and option.g:
    print("总内存为:%.2f" %(total_mem/1024/1024) + " GB")
    print("剩余可用内存为:%.2f" %(free_mem/1024/1024) + " GB")
    print("剩余内存可用比例为:%d" %(x*100) + "%" )
else:
    pass


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇使用Python实现简单Linux之find命.. 下一篇使用Python实现Linux系统wc命令

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目