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

yipeiwu_com5年前Python基础

本文以实例形式实现了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()

相关文章

python安装requests库的实例代码

requests是python实现的简单易用的HTTP库,使用起来比urllib简洁很多 因为是第三方库,所以使用前需要cmd安装 pip install requests 安装完...

代码详解django中数据库设置

首先定义数据库的表名和字段 启动mysql数据库 bash mysql.server start 安装pymysql pip install pymysql PyMySQL 是在 Pyt...

Python获取DLL和EXE文件版本号的方法

本文实例讲述了Python获取DLL和EXE文件版本号的方法。分享给大家供大家参考。具体实现方法如下: 复制代码 代码如下:import win32api def getFileVers...

Python执行时间的计算方法小结

首先说一下我遇到的坑,生产上遇到的问题,我调度Python脚本执行并监控这个进程,python脚本运行时间远远大于python脚本中自己统计的程序执行时间。 监控python脚本执行...

python替换字符串中的子串图文步骤

python替换字符串中的子串图文步骤

修改字符串本身是不可能的,因为字符串是不可变类型,只能是通过某些方法来产生它的副本。再把副本赋值给原字符串,达到类似替换的作用。这里介绍几种方法。 旧串换新串:使用str.replace...