python实现监控linux性能及进程消耗性能的方法
本文以实例形式实现了python监控linux性能以及进程消耗性能的方法,具体实现代码如下:
#-*-coding:utf-8-*- """ CreatedonTueJun1010:20:132014 @author:lifeix """ fromcollectionsimportOrderedDict importtime importos defcpuinfo(): lines=open('/proc/stat').readlines() forlineinlines: ln=line.split() ifln[0].startswith('cpu'): returnln; 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]) defCPUinfo(): '''Returntheinformationin/proc/CPUinfo asadictionaryinthefollowingformat: CPU_info['proc0']={...} CPU_info['proc1']={...} ''' CPUinfo=OrderedDict() procinfo=OrderedDict() nprocs=0 f=open('/proc/cpuinfo') forlineinf.readlines(): ifnotline.strip(): #endofoneprocessor CPUinfo['proc%s'%nprocs]=procinfo nprocs=nprocs+1 #Reset procinfo=OrderedDict() else: iflen(line.split(':'))==2: procinfo[line.split(':')[0].strip()]=line.split(':')[1].strip() else: procinfo[line.split(':')[0].strip()]='' returnCPUinfo defmeminfo(): '''Returntheinformationin/proc/meminfo asadictionary''' meminfo=OrderedDict() f=open('/proc/meminfo') forlineinf.readlines(): meminfo[line.split(':')[0]]=line.split(':')[1].strip() returnmeminfo f=open("sysinfo.log",'a') deflogSysInfo(cpu,mem,line): f.write('\ncpu:%s-------mem:%s------mongocpu:%s'%(cpu,mem,line)) f.flush(); defprocess_info(): #获取drm_processes的进程号 textlist=os.popen('top-bcn1-p12023').readlines() line='' fortintextlist: ift.find('12023'): line=t line=line.split('') #此处的值按照自己的需求去取 returnline[15] if__name__=='__main__': CPUinfo=CPUinfo() forprocessorinCPUinfo.keys(): print(CPUinfo[processor]['modelname']) f.write("cpu:%s"%CPUinfo[processor]['modelname']) #meminfo=meminfo() #print('Totalmemory:{0}'.format(meminfo['MemTotal'])) try: whileTrue: line=process_info() time.sleep(2) mi=meminfo() print('Freememory:{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)) printline cpu='%.2f%%'%(cpuused*100) logSysInfo(cpu,format(mi['MemFree']),line) exceptKeyboardInterrupt,e: print("\ncpumonitexited") f.close() f.close()