python脚本获取进程使用内存情况

[root@zabbix-server ~]# cat mem.py 
#!/usr/bin/env python
# _*_ coding:UTF-8 _*_
# 收集程序所占用的物理内存大小,占所有物理内存的比例
# Python: 2.7.6

import sys
import os
from subprocess import Popen,PIPE

def get_pid(program):
    '获取目标程序的PID列表'
    p = Popen(['pidof',program],stdout=PIPE,stderr=PIPE)
    pids,stderrput = p.communicate()
#     pids = p.stdout.read()  #这种方法也是可以的
#     这里也可以对stderrput来进行判断
    if pids:
        return pids.split()
    else:
        raise ValueError

def mem_calc(pids):
    '计算PIDs占用的内存大小'
    mem_total = 0
    for pid in pids:
        os.chdir('/proc/%s' % pid)
        with open('status') as fd:
            for line in fd:
                if line.startswith('VmRSS'):
                    mem = line.strip().split()[1]
                    mem_total += int(mem)
                    break
    return mem_total


def mem_percent(mem):
    '计算程序内存占用物理内存的百分比'
    with open('/proc/meminfo') as fd:
        for line in fd:
            if line.startswith('MemTotal'):
                total = line.strip().split()[1]
        percent = (float(mem)/int(total)) * 100
    return percent


def main():
    try:
        program = sys.argv[1]
        pids = get_pid(program)
    except IndexError as e:
        sys.exit('%s need a Program name ' % __file__)
    except ValueError as e:
        sys.exit('%s not a Process Name or not Start' % program )
    mem_total = mem_calc(pids)
    percent = mem_percent(mem_total)
    return program,mem_total,percent

if __name__ == '__main__':
    program,mem_total,mem_percent=main()
    print('进程名称:%s\n物理内存为:%s\n百分比为:%.2f%%'% (program,mem_total,mem_percent))


[root@zabbix-server ~]# python mem.py  zabbix_agentd
进程名称:zabbix_agentd
物理内存为:12332
百分比为:1.24%

[root@zabbix-server ~]# python mem.py  zabbix_server
进程名称:zabbix_server
物理内存为:115300
百分比为:11.58%

[root@zabbix-server ~]# python mem.py  httpd
进程名称:httpd
物理内存为:212148
百分比为:21.30%
posted @ 2023-11-06 11:06  普里莫  阅读(119)  评论(0编辑  收藏  举报