#!/usr/bin/python
import signal
import os
import sys
import re
import string
import time
import commands
exit = 0;
def getPID(ProcessName,PIDHash):
pidstr = os.popen('ps -e').readlines();
#print pidstr;
PIDWatch = [];
TmpRe = [];
for p in ProcessName:
TmpRe.append(re.compile('\s*([0-9]+).*(' + p + ')$'));
for line in pidstr:
#print line;
for tmpre in TmpRe:
result = tmpre.match(line);
if result:
PIDWatch.append(result.group(1));
PIDHash[result.group(1)] = [result.group(1), result.group(2), 0.0, 0, 0.0, 0.0, 10000.0];
return PIDWatch;
def getPIDCpuInfo(PIDWatch,PIDHash):
if len(PIDWatch)==0:
return;
topcmd = [];
for p in PIDWatch:
topcmd.append('top -n 1 -p '+ p);
while 1:
flag = 0;
print '-------------------------------------------';
for cmd in topcmd:
status,line = commands.getstatusoutput(cmd);
#print line;
line.strip();
Info = line.split();
#print Info;
for p in PIDWatch:
#print Info[-14], Info[-3], Info[-6], Info[-14];
if len(Info) > 14 and PIDHash[p][0] in Info[-14] :
flag = 1;
PIDHash[p][2] += float(Info[-6]);
PIDHash[p][3] += 1;
PIDHash[p][4] = float(PIDHash[p][2])/float(PIDHash[p][3]);
if float(Info[-6]) > float(PIDHash[p][5]):
PIDHash[p][5] = float(Info[-6]);
if float(Info[-6]) < float(PIDHash[p][6]):
PIDHash[p][6] = float(Info[-6]);
print "%-10s%-6s%.2f %.2f %.2f"%(PIDHash[p][0], PIDHash[p][1], PIDHash[p][4], PIDHash[p][5], PIDHash[p][6]);
global exit;
if flag == 0 or exit == 1:
break;
time.sleep(1);
def handler(signum, frame):
global exit;
exit = 1;
signal.signal(signal.SIGTERM,handler);
signal.signal(signal.SIGINT, handler);
signal.signal(signal.SIGALRM, handler);
if __name__ == "__main__":
PIDHash = {};
PIDWatch = getPID(sys.argv[1:],PIDHash);
#print sys.argv[1:];
#print PIDWatch;
print 'PID Process AVERAGE MAX MIN';
getPIDCpuInfo(PIDWatch,PIDHash);
|