欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python实现监控linux性能及进程消耗性能的方法

程序员文章站 2022-05-14 09:07:33
本文以实例形式实现了python监控linux性能以及进程消耗性能的方法,具体实现代码如下: # -*- coding: utf-8 -*- """ crea...

本文以实例形式实现了python监控linux性能以及进程消耗性能的方法,具体实现代码如下:

# -*- coding: utf-8 -*-
"""
created on tue jun 10 10:20:13 2014

@author: lifeix
"""

from collections import ordereddict
import time
import os

def cpuinfo():
  lines = open('/proc/stat').readlines()
  for line in lines:
    ln = line.split()
    if ln[0].startswith('cpu'):
      return ln;
  return []
w = cpuinfo()
one_cputotal=long(w[1])+long(w[2])+long(w[3])+long(w[4])+long(w[5])+long(w[6])+long(w[7])
one_cpuused=long(w[1])+long(w[2])+long(w[3])

def cpuinfo():
  ''' return the information in /proc/cpuinfo
  as a dictionary in the following format:
  cpu_info['proc0']={...}
  cpu_info['proc1']={...}
  '''
  cpuinfo=ordereddict()
  procinfo=ordereddict()

  nprocs = 0
  f = open('/proc/cpuinfo')
  for line in f.readlines():
    if not line.strip():
      # end of one processor
      cpuinfo['proc%s' % nprocs] = procinfo
      nprocs=nprocs+1
      # reset
      procinfo=ordereddict()
    else:
      if len(line.split(':')) == 2:
        procinfo[line.split(':')[0].strip()] = line.split(':')[1].strip()
      else:
        procinfo[line.split(':')[0].strip()] = ''
  return cpuinfo

def meminfo():
  ''' return the information in /proc/meminfo
  as a dictionary '''
  meminfo=ordereddict()

  f = open('/proc/meminfo')
  for line in f.readlines():
    meminfo[line.split(':')[0]] = line.split(':')[1].strip()
  return meminfo

f = open("sysinfo.log",'a')
def logsysinfo(cpu,mem,line):
  f.write('\ncpu:%s -------mem: %s------mongocpu:%s'%(cpu,mem,line))
  f.flush();

def process_info():
  #获取drm_processes 的进程号
  textlist = os.popen('top -bcn 1 -p 12023').readlines()
  line = ''
  for t in textlist:
    if t.find('12023'):
      line = t
  line = line.split(' ')
  #此处的值按照自己的需求去取
  return line[15]
if __name__=='__main__':
  cpuinfo = cpuinfo()
  for processor in cpuinfo.keys():
    print(cpuinfo[processor]['model name'])
    f.write("cpu:%s"%cpuinfo[processor]['model name'])
  #meminfo = meminfo()
  #print('total memory: {0}'.format(meminfo['memtotal'])) 

  try:
    while true:
      line = process_info()
      time.sleep(2)
      mi = meminfo()
      print('free memory: {0}'.format(mi['memfree']))
      w = cpuinfo()
      two_cputotal=long(w[1])+long(w[2])+long(w[3])+long(w[4])+long(w[5])+long(w[6])+long(w[7])
      two_cpuused=long(w[1])+long(w[2])+long(w[3])
      cpuused=float(two_cpuused-one_cpuused)/(two_cputotal-one_cputotal)
      print ('%.2f%%'%(cpuused*100))
      print line
      cpu = '%.2f%%'%(cpuused*100)
      logsysinfo(cpu,format(mi['memfree']),line)
  except keyboardinterrupt, e:
    print ("\ncpumonit exited")
    f.close()
f.close()