zoukankan      html  css  js  c++  java
  • 【原创】面向对象版本地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())+'
    ')
                    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())+'
    ')
                    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()
  • 相关阅读:
    把梳子卖给和尚 引起的CRM
    windows 2008 r2 安装 owas 2013
    wopihost
    电商创业,你到底需要多少人的技术团队?
    信息化,并不能代替管理
    可遇不可求的Question之error: Failed dependencies: MySQLconflicts 错误篇
    可遇不可求的Question之flash的socket连接安全策略文件篇
    可遇不可求的Question之MySQL系统变量interactive_timeout 与 wait_timeout 篇
    可遇不可求的Question之导入mysql中文乱码解决方法篇
    Codesmith怎么判断sqlserver数据库字段是不是标识自增字段
  • 原文地址:https://www.cnblogs.com/huangxiaocheng/p/9040518.html
Copyright © 2011-2022 走看看