This article implements Python's method of monitoring Linux performance and process consumption performance in an instance form, implementing the following code:
#-*-Coding:utf-8-*-"" "Created on Tue June 10:20:13 2014 @author: Lifeix" "" from collections import ordereddict
Import time import os def cpuinfo (): lines = open ('/proc/stat '). ReadLines () to 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 Dictiona
Ry 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 L ine 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 process Number textlist = Os.popen (' TOP-BCN 1-p 12023 '). ReadLines () line = "For t i n 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.W Rite ("cpu:%s"%cpuinfo[processor][' model name ') #meminfo = Meminfo () #print (' Total memory: {0} '. Format (meminfo[' Memto Tal ']) try:whileTrue:line = Process_info () time.sleep (2) mi = Meminfo () print (' free memory: {0} '. Format (mi[' MEMFR
EE ']) 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_cputota L) Print ('%.2f%% '% (cpuused*100)) Print line CPU = '%.2f%% '% (cpuused*100) logsysinfo (mi
[' Memfree ']), line) except Keyboardinterrupt, E:print ("\ncpumonit exited") F.close () F.close ()