read_load_average.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #coding:utf-8
  2. import datetime
  3. import os
  4. import re
  5. import sys
  6. import subprocess
  7. import time
  8. pid_cpu_dict = {}
  9. pid_cmd_dict = {}
  10. def read_top():
  11. ps = os.popen('top -n 1 -b | sed -n 8,18p').readlines()
  12. for line in ps:
  13. ls = []
  14. for l in line.split(" "):
  15. if l:
  16. ls.append(l)
  17. print("top ls", ls)
  18. cpu = float(ls[8])
  19. pid = ls[0]
  20. ps_cmd = read_ps(pid)
  21. if not ps_cmd or "top" in ps_cmd:
  22. continue
  23. if pid in pid_cpu_dict:
  24. pid_cpu_dict[pid] = (pid_cpu_dict[pid] + cpu) / 2
  25. else:
  26. pid_cpu_dict[pid] = cpu
  27. if pid not in pid_cmd_dict:
  28. pid_cmd_dict[pid] = ps_cmd
  29. pid_cpu_list = [[k, pid_cpu_dict.get(k)] for k in pid_cpu_dict.keys()]
  30. pid_cpu_list.sort(key=lambda x: x[1], reverse=True)
  31. print("*"*30)
  32. print(datetime.datetime.now())
  33. for pid, cpu in pid_cpu_list:
  34. print(pid, cpu, pid_cmd_dict.get(pid))
  35. print("*"*30)
  36. def read_ps(pid):
  37. ps = os.popen('ps -f -p ' + str(pid) + ' | sed -n 2p').readlines()
  38. line = []
  39. if ps:
  40. for l in ps[0].split(" "):
  41. if l:
  42. line.append(l)
  43. # print("ps ls", line)
  44. find_flag = 0
  45. cmd = ""
  46. for l in line:
  47. if find_flag:
  48. cmd += l
  49. if ":" in l:
  50. find_flag = 1
  51. cmd = cmd[:-1]
  52. return cmd
  53. if __name__ == "__main__":
  54. for i in range(10000):
  55. read_top()
  56. time.sleep(5)
  57. # read_ps(31823)