【原创】面向对象版本地CPU资源占用监控脚本

2018-06-18 02:55:32来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

前期准备:

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()

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:python:Json模块dumps、loads、dump、load介绍

下一篇:铁乐学python_Day38_多进程和multiprocess模块1