计算程序的内存和占比

 1 #!/usr/bin/env python
 2 # _*_ coding:UTF-8 _*_
 3 # 收集程序所占用的物理内存大小,占所有物理内存的比例
 4 # OS: Centos 6.7  Python: 2.7.6 
 5 # __author__:Dahlhin
 6 
 7 import sys
 8 import os
 9 from subprocess import Popen,PIPE
10 
11 def get_pid(program):
12     '获取目标程序的PID列表'
13     p = Popen(['pidof',program],stdout=PIPE,stderr=PIPE)
14     pids,stderrput = p.communicate()
15 #     pids = p.stdout.read()  #这种方法也是可以的
16 #     这里也可以对stderrput来进行判断
17     if pids:
18         return pids.split()
19     else:
20         raise ValueError
21 
22 def mem_calc(pids):
23     '计算PIDs占用的内存大小'
24     mem_total = 0
25     for pid in pids:
26         os.chdir('/proc/%s' % pid)
27         with open('status') as fd:
28             for line in fd:
29                 if line.startswith('VmRSS'):
30                     mem = line.strip().split()[1]
31                     mem_total += int(mem)
32                     break
33     return mem_total
34 
35 
36 def mem_percent(mem):
37     '计算程序内存占用物理内存的百分比'
38     with open('/proc/meminfo') as fd:
39         for line in fd:
40             if line.startswith('MemTotal'):
41                 total = line.strip().split()[1]
42         percent = (float(mem)/int(total)) * 100
43     return percent
44 
45 
46 def main():
47     try:
48         program = sys.argv[1]
49         pids = get_pid(program)
50     except IndexError as e:
51         sys.exit('%s need a Program name ' % __file__)
52     except ValueError as e:
53         sys.exit('%s not a Process Name or not Start' % program )
54     mem_total = mem_calc(pids)
55     percent = mem_percent(mem_total)
56     return program,mem_total,percent
57 
58 if __name__ == '__main__':
59     program,mem_total,mem_percent=main()
60     print('进程名称:%s\n物理内存为:%s\n百分比为:%.2f%%'% (program,mem_total,mem_percent))

 

posted @ 2017-05-05 12:00  SpeicalLife  阅读(1325)  评论(0编辑  收藏  举报