原创面向对象版本地CPU资源占用监控脚本
Posted huangxiaocheng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了原创面向对象版本地CPU资源占用监控脚本相关的知识,希望对你有一定的参考价值。
前期准备:
1.python2.7环境
2.相关第三方库下载安装
脚本工作过程:
1.根据输入的进程名判断进程是否存在,如果不存在则进行等待,直到检测到进程PID,中途进程退出抛出异常,键入enter后等待进程重启
实际作用:
1.可以重复监控某一进程CPU资源占用情况,结果同步到本地D盘文本保存
#coding=utf-8 import psutil import sys import time import win32com.client class Cpu(): def __init__(self,name): self.name=name def pid(self): for proc in psutil.process_iter(): pinfo = proc.as_dict(attrs=[‘pid‘, ‘name‘]) # key_pid = list(pinfo)[0] key_pid_value = list(pinfo.values())[0] # key_name = list(pinfo)[1] key_name_value = list(pinfo.values())[1] if key_name_value == self.name: return key_pid_value def get_cpu_info(self): # reload(sys) # sys.setdefaultencoding(‘utf-8‘) filename = ‘D:\\‘ + ‘CPU_usage_result‘ + str(int(time.time())) + ".txt" text = open(filename, ‘w‘) while True: cpucount = psutil.cpu_count(logical=True) process = psutil.Process(int(PID)) cpupercent = process.cpu_percent(interval=2) cpu = int(cpupercent / cpucount) if cpu <= 50: print ‘cpu usage:%s%%‘ % cpu + ‘ ‘ + time.strftime(‘%Y-%m-%d %H:%M:%S‘, time.localtime()) text.write(‘cpu usage:%s%%‘ % cpu + ‘ ‘ + time.strftime(‘%Y-%m-%d %H:%M:%S‘, time.localtime())+‘\n‘) text.flush() else: print ‘cpu usage:%s%%,too high‘ % cpu + ‘ ‘ + time.strftime(‘%Y-%m-%d %H:%M:%S‘, time.localtime()) text.write(‘cpu usage:%s%%‘ % cpu + ‘ ‘ + time.strftime(‘%Y-%m-%d %H:%M:%S‘, time.localtime())+‘\n‘) text.flush() # text.close() def CheckProcExistByPN(self): try: WMI = win32com.client.GetObject(‘winmgmts:‘) processCodeCov = WMI.ExecQuery(‘select * from Win32_Process where Name="%s"‘ % self.name) except Exception, e: print "error : ", e if len(processCodeCov) > 0: # print name + " exist" return 1 else: # print name + " is not exist" return 0 if __name__==‘__main__‘: ProcessName = raw_input(‘ProcessName: ‘) reslut=Cpu(ProcessName) while True: try: if reslut.CheckProcExistByPN() == 1: PID = reslut.pid() print ‘Process %s‘ % PID +‘ ‘+‘result in D:\\CPU_usage_result.txt‘ time.sleep(1) print "-------------------------------------------------" print reslut.get_cpu_info() else: print ‘Wait for process start‘+ ‘ ‘ +time.strftime(‘%Y-%m-%d %H:%M:%S‘, time.localtime()) time.sleep(1) except Exception, e: print "Quit : ", e raw_input()
以上是关于原创面向对象版本地CPU资源占用监控脚本的主要内容,如果未能解决你的问题,请参考以下文章