本文共 1206 字,大约阅读时间需要 4 分钟。
#!/usr/bin/env python#encoding: utf-8'''思路: /proc/xx_pid/status 文件中的关键字段 VmRSS 来获取某个进程占用的物理内存步骤: 获取 httpd 进程ID列表 --> 通过每个进程id来获取该进程占用物理内存'''from subprocess import Popen, PIPEimport os,sys# 通过程序名称获取 pid 列表def getProgPids(prog): p = Popen(['pidof', prog], stdout=PIPE, stderr=PIPE) pids = p.stdout.read().split() return pids# 通过具体的进程 id 来获取该进程占用的物理内存def getMemByPid(pid): fn = os.path.join('/proc', pid, 'status') with open(fn) as fd: for line in fd: if line.startswith('VmRSS'): mem = int(line.split()[1]) break return mem# 获取 httpd 服务所有进程占用的物理内存def getHttpdMem(): httpd_mem_sum = 0 pids = getProgPids('httpd') for pid in pids: httpd_mem_sum += getMemByPid(pid) return httpd_mem_sum# 获取系统总的物理内存def getOsTotalMemory(): with open('/proc/meminfo') as fd: for line in fd: if line.startswith('MemTotal'): total_mem = int(line.split()[1]) break return total_memif __name__ == '__main__': http_mem = getHttpdMem() total_mem = getOsTotalMemory() scale = http_mem / float(total_mem) * 100 print 'Httpd: %d KB' % http_mem print 'Percent: %.2f%%' % scale
转载地址:http://xjzxx.baihongyu.com/