#coding:utf-8 import datetime import os import re import sys import subprocess import time pid_cpu_dict = {} pid_cmd_dict = {} def read_top(): ps = os.popen('top -n 1 -b | sed -n 8,18p').readlines() for line in ps: ls = [] for l in line.split(" "): if l: ls.append(l) print("top ls", ls) cpu = float(ls[8]) pid = ls[0] ps_cmd = read_ps(pid) if not ps_cmd or "top" in ps_cmd: continue if pid in pid_cpu_dict: pid_cpu_dict[pid] = (pid_cpu_dict[pid] + cpu) / 2 else: pid_cpu_dict[pid] = cpu if pid not in pid_cmd_dict: pid_cmd_dict[pid] = ps_cmd pid_cpu_list = [[k, pid_cpu_dict.get(k)] for k in pid_cpu_dict.keys()] pid_cpu_list.sort(key=lambda x: x[1], reverse=True) print("*"*30) print(datetime.datetime.now()) for pid, cpu in pid_cpu_list: print(pid, cpu, pid_cmd_dict.get(pid)) print("*"*30) def read_ps(pid): ps = os.popen('ps -f -p ' + str(pid) + ' | sed -n 2p').readlines() line = [] if ps: for l in ps[0].split(" "): if l: line.append(l) # print("ps ls", line) find_flag = 0 cmd = "" for l in line: if find_flag: cmd += l if ":" in l: find_flag = 1 cmd = cmd[:-1] return cmd if __name__ == "__main__": for i in range(10000): read_top() time.sleep(5) # read_ps(31823)