zoukankan      html  css  js  c++  java
  • 使用Python统计Linux系统内存使用率

    #!/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
    
    
  • 相关阅读:
    安装devstack之配置proxy
    设备信息表项目
    好的运维工程师
    rhel 6.4 增加光盘为yum repo
    深度运维产品工具关键词
    坚持是一种能力
    书单 电影单 电视剧单
    三日不读书,便觉得言语无味,面目可憎
    STAR法则
    【断舍离】
  • 原文地址:https://www.cnblogs.com/MeiCheng/p/11555455.html
Copyright © 2011-2022 走看看