Introduction
With the Psutil module (https://pypi.python.org/pypi/psutil/), it is very convenient to monitor the system's CPU, memory, disk IO, network bandwidth and other performance parameters, whether the following code to monitor the CPU resource consumption of a particular program, Prints the monitoring data, the final drawing is displayed, and is saved as a backup of the specified PDF document.
Demo Code
#!/usr/bin/env python#-*-coding:utf-8-*-"Copyright (C) by Thomas Hu. All rights reserved. @author: Thomas Hu (thomashtq#163.com) @version: 1.0@created:2015-7-14 "Import Matplotlib.pyplot As Pltimport Psutil as Psimport osimport timeimport randomimport collectionsimport argparseclass ProcessMonitor (object): def __init__ (self, Key_name, fields, duration, interval): Self.key_name = key_name self.fields = Fields Self.duration = float (duration) self.inveral = float (interval) self. Cpu_count = Ps.cpu_count () self. Mem_total = Ps.virtual_memory (). Total/(1024x768 * 1024x768) self.procinfo_dict = Collections.defaultdict (dict) def _ge T_proc_info (self, pid): Try:proc = PS. Process (PID) name = Proc.name () # If not contains the key word, return None if Name.find ( self.key_name) = = -1:return None pinfo = {"Name": Name, "pid": PID,} # If The field is correct, add it to the process information dictionary. For field in Self.fields:if hasattr (proc, field): if field = = "Cpu_percent": Pinfo[field] = GetAttr (proc, field) (interval = 0.1)/self. Cpu_count elif field = = "Memory_percent": pinfo[field] = GetAttr (proc, field) () * Self. mem_total/100 Else:pinfo[field] = GetAttr (proc, field) () if PID no T in self.procinfo_dict:self.procinfo_dict[pid] = collections.defaultdict (list) self.procin fo_dict[pid]["name"] = name for field in Self.fields:self.procinfo_dict[pid][field].append (Pinf O.get (field, 0)) print (pinfo) return pinfo Except:pass return None def Monitor_processes (self): start = Time.time () and while TIme.time ()-start < Self.duration:try:pids = Ps.pids () for PID in PIDs: Self._get_proc_info (PID) except Keyboardinterrupt:print ("Killed by user Keyboar D interrupted! ") return def _get_color (self): color = ' # ' for I in Range (3): a = Hex (random.randint (0, 255)) [2: ] If Len (a) = = 1:a = "0" + a color + a return color.upper () def Draw_figu Re (self, field, pdf): # Draw all PID line for PID in self.procinfo_dict:x = Range (len (self.proc Info_dict[pid][field])) #print x, Self.procinfo_dict[pid][field] Plt.plot (x, Self.procinfo_dict[pid] [Field], label = "pid" + STR (PID), color = Self._get_color ()) Plt.xlabel (Time.strftime ("%y-%m-%d%h:%m:%s")) Plt.ylabel (Field.upper ()) Plt.title (field + "figure") plt.legend (loc = "upper Left") plt.grID (True) plt.savefig (PDF, DPI = $) plt.show () def Main (): parser = Argparse. Argumentparser (description= ' Monitor process CPU and Memory. ') Parser.add_argument ("-K", dest= ' key ', Type=str, default= "producer", help= ' the key word of the processes to being monitored (default is "producer") Parser.add_argument ("-D", dest= ' duration ', type=int, default=60, Help= ' duration of the monitor to run (Unit:seconds, default is) ') parser.add_argument ('-i ', dest= ' interval ', t Ype=float, default=1.0, help= ' Interval of the sample (Unit:seconds, default is 1.0) ') args = PARSER.P Arse_args () fields = ["Cpu_percent", "memory_percent"] #print Args.key, args.duration, args.interval pm = Process Monitor (Args.key, Fields, Args.duration, Args.interval) pm.monitor_processes () pm.draw_figure ("Cpu_percent", "cpu.pd F ") Pm.draw_figure (" Memory_percent "," mem.pdf ") if __name__ = =" __main__ ": Main ()
Output Sample Diagram