python开发: linux进程占用物理内存

#!/usr/bin/env python
#-*- coding:utf-8 -*-

''' 统计linux进程占用的物理内存 '''

import os
import sys
import subprocess

def getPidList(proc):
    cmd = '''/sbin/pidof %s''' % proc
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
    pidList = p.stdout.read().split()
    return pidList


def getMemSize(pidList):
    sum = 0
    for pid in pidList:
        filename = os.path.join('/proc', pid, 'status')
        with open(filename) as fd:
             for line in fd.readlines():
                 if line.startswith('VmRSS'):
                     memSize = int(line.split()[1])
                     sum += memSize
                     break
    return sum

if __name__ == '__main__':
    proc = sys.argv[1]
    pidList = getPidList(proc)
    totalMem = getMemSize(pidList)
    unit = 'KB'
    if totalMem > 1024:
        totalMem = totalMem / 1024
        unit = 'MB'
    print('%s占用物理内存:%.2f %s' % (proc.capitalize(), totalMem, unit))
pidof命令不识别则系统需要安装
posted @ 2020-06-22 15:49  jiangcheng_15  阅读(495)  评论(0编辑  收藏  举报