psutil api文档:

http://pythonhosted.org/psutil/

api 测试

  1. #! /usr/bin/env python
  2. # coding=utf-8
  3.  
  4. import psutil
  5.  
  6. # CPU-> Examples
  7.  
  8. # print psutil.cpu_times()
  9. # print psutil.cpu_count()
  10. # print psutil.cpu_count(logical=False)
  11. #
  12. # for x in range(3):
  13. # print psutil.cpu_percent(interval=1)
  14. # print psutil.cpu_percent(interval=1, percpu=True)
  15. # print psutil.cpu_times_percent(interval=1, percpu=False)
  16.  
  17. # Memory-> Examples:
  18.  
  19. # print psutil.virtual_memory()
  20. # print psutil.swap_memory()
  21.  
  22. # Disks-> Examples:
  23.  
  24. # print psutil.disk_partitions()
  25. # print psutil.disk_usage('/')
  26. # print psutil.disk_io_counters(perdisk=False)
  27.  
  28. # Networks-> Examples:
  29.  
  30. # print psutil.net_io_counters(pernic=True)
  31. # print psutil.net_connections()
  32.  
  33. # Other system info-> Examples:
  34.  
  35. # print psutil.users()
  36. # print psutil.boot_time()
  37.  
  38. # Process Management-> Examples:
  39.  
  40. print psutil.pids()
  41.  
  42. for i in psutil.pids():
  43. p = psutil.Process(i)
  44. # print p.name(), p.cpu_percent(interval=1.0)
  45.  
  46. # print p.name()
  47. # print p.cmdline()
  48. # print p.exe()
  49. # print p.cwd()
  50. # print p.status()
  51. # print p.username()
  52. # print p.create_time()
  53.  
  54. # print p.terminal()
  55. # print p.uids()
  56. # print p.gids()
  57.  
  58. # print p.cpu_times()
  59. # print p.cpu_percent(interval=1.0)
  60.  
  61. # print p.cpu_affinity()
  62. # print p.cpu_affinity([0])
  63.  
  64. # print p.memory_percent()
  65. # print p.memory_info()
  66. # print p.ext_memory_info()
  67. # print p.memory_maps()
  68. # print p.io_counters()
  69. # print p.open_files()
  70. # print p.connections()
  71. # print p.num_threads()
  72. # print p.num_fds()
  73. # print p.threads()
  74. # print p.num_ctx_switches()
  75. # print p.nice()
  76. # print p.nice(10)
  77.  
  78. # print p.ionice(psutil.IOPRIO_CLASS_IDLE) # IO priority (Win and Linux only)
  79. # print p.ionice()
  80. # print p.rlimit(psutil.RLIMIT_NOFILE, (5, 5)) # set resource limits (Linux only)
  81. # print p.rlimit(psutil.RLIMIT_NOFILE)
  82.  
  83. # print p.suspend()
  84. # print p.resume()
  85. # print p.terminate()
  86. # print p.wait(timeout=3)
  87.  
  88. print psutil.test()

配置:

  1. process:
  2. name: ProxyTool.exe
  3. path: E:\Project\ProxyTool.exe
  4.  
  5. rules:
  6.  
  7. p_cpu_percent: 100
  8. #t_cpu_percent: 20
  9. #cpu_times: 30
  10. #num_threads: 15
  11. #connections: 20
  12.  
  13. noporcesssleeptime: 3
  14. getprocinfotimespan: 3
  15. cpupercentinterval: 1

config.yaml

转换exe

  1. #! /usr/bin/env python
  2. # coding=utf-8
  3.  
  4. '''
  5. Created on 2015.10.12
  6.  
  7. @author: ryhan
  8. '''
  9.  
  10. import os
  11.  
  12. # 以下代码解决输出乱码问题
  13. import sys
  14. # print sys.getdefaultencoding()
  15. reload(sys)
  16. sys.setdefaultencoding('utf-8')
  17. # print sys.getdefaultencoding()
  18.  
  19. Py_Installer_Path='D:\pyinstaller-develop'
  20. Py_FilePATH = "%s\\" % (os.path.dirname(os.path.realpath(__file__)),)
  21. Py_FileList=['MyProcMonitor']
  22.  
  23. # print Py_FilePATH
  24.  
  25. os.chdir(Py_Installer_Path)
  26.  
  27. for fname in Py_FileList:
  28.  
  29. #cmd='python pyinstaller.py --upx-dir=D:\pyinstaller-develop\upx391w -F %s%s.py' % (Py_FilePATH,fname)
  30. #upx.exe 放入到python安装路径下 如果不想使用upx,需要添加参数 --noupx
  31. cmd='python pyinstaller.py -F %s%s.py' % (Py_FilePATH,fname)
  32. print cmd
  33. os.system(cmd)
  34.  
  35. cmd='copy /y %s\%s\dist\%s.exe %s' % (Py_Installer_Path,fname,fname,Py_FilePATH)
  36. print cmd
  37. os.system(cmd)

BulidExe

主程:

  1. #! /usr/bin/env python
  2. # coding=utf-8
  3.  
  4. import psutil
  5. # print psutil.test()
  6.  
  7. import functools
  8. import yaml
  9. import json
  10. import time
  11. import os
  12.  
  13. from pylog import logger
  14.  
  15. def log(func):
  16. @functools.wraps(func)
  17. def wrapper(*args, **kw):
  18.  
  19. logger.debug(u'---- Invoke : %s ----' , func.__name__)
  20.  
  21. return func(*args, **kw)
  22. return wrapper
  23.  
  24. class Monitor():
  25.  
  26. @log
  27. def __init__(self):
  28.  
  29. self.confd = yaml.load(file('config.yaml'))
  30. logger.debug('yaml:%s', self.confd)
  31.  
  32. if(self.confd == None or self.confd.get('process') == None or self.confd.get('rules') == None or len(self.confd.get('rules')) == 0):
  33. raise ValueError('please check config.yaml~! (key: confprocess or rules)')
  34.  
  35. self.confprocname = self.confd.get('process', '{}').get('name', '')
  36. self.confprocpath = self.confd.get('process', '{}').get('path', '')
  37. self.confrules = self.confd.get('rules')
  38.  
  39. self.noporcesssleeptime = self.confd.get('noporcesssleeptime', 3)
  40. self.getprocinfospantime = self.confd.get('getprocinfotimespan', 1)
  41. self.cpupercentinterval = self.confd.get('cpupercentinterval', 1)
  42.  
  43. @log
  44. def __loadProcess(self):
  45.  
  46. self.monitorproc = None
  47.  
  48. try:
  49. for p in psutil.process_iter():
  50. # pinfo = p.as_dict(attrs=['pid', 'name'])
  51.  
  52. # for pid in psutil.pids():
  53. # p = psutil.Process(pid)
  54.  
  55. if p.name() == self.confprocname:
  56. self.monitorproc = p
  57. break
  58.  
  59. if(self.monitorproc):
  60. logger.info('Findprocess %s: id:%s ', self.confprocname, self.monitorproc.pid)
  61. else:
  62. logger.info('Do Not Find Porcess ! Please Check~!')
  63.  
  64. except Exception, e:
  65. logger.debug(e)
  66.  
  67. return self.monitorproc
  68.  
  69. @log
  70. def loopControl(self):
  71.  
  72. logger.info('Begin while loop!')
  73.  
  74. finprocessloop = 1
  75.  
  76. while 1:
  77. try:
  78. while finprocessloop:
  79. if(not self.__loadProcess()):
  80. time.sleep(self.noporcesssleeptime)
  81. continue
  82. else:
  83. finprocessloop = 0
  84.  
  85. args = self.__getProcInfo()
  86. if args and args[0]:
  87. self.__checkProc(*args)
  88. else:
  89. logger.info('Missing Process Control: %s !', self.confprocname)
  90. finprocessloop = 1
  91.  
  92. time.sleep(self.getprocinfospantime)
  93.  
  94. except Exception, e:
  95. logger.debug('loopControl.while :%s', e)
  96.  
  97. @log
  98. def __getProcInfo(self):
  99.  
  100. try:
  101. p = self.monitorproc
  102. pinf = {}
  103.  
  104. pinf['id'] = p.pid
  105. pinf['name'] = p.name()
  106. # pinf['exe'] = p.exe()
  107. pinf['num_threads'] = p.num_threads()
  108. pinf['num_handles'] = p.num_handles()
  109. pinf['threads'] = p.threads()
  110. pinf['connections'] = p.connections()
  111. pinf['memory_percent'] = p.memory_percent()
  112. pinf['memory_info'] = p.memory_info()
  113. pinf['cpu_affinity'] = p.cpu_affinity()
  114. pinf['cpu_times'] = p.cpu_times()
  115. pinf['p_cpu_percent'] = p.cpu_percent(interval=self.cpupercentinterval)
  116. pinf['t_cpu_percent'] = psutil.cpu_percent(interval=self.cpupercentinterval)
  117. pinf['cpu_count_real'] = psutil.cpu_count()
  118. pinf['cpu_count_logical'] = psutil.cpu_count(logical=False)
  119.  
  120. cpu_count_real = pinf['cpu_count_real']
  121. cpu_count_logical = pinf['cpu_count_logical']
  122. p_cpu_percent = pinf['p_cpu_percent']
  123. t_cpu_percent = pinf['t_cpu_percent']
  124.  
  125. logger.debug('pinfo:%s', pinf)
  126. # logger.debug('p_cpu_percent:%s', p_cpu_percent)
  127. # logger.debug('t_cpu_percent:%s', t_cpu_percent)
  128.  
  129. return (True, p_cpu_percent, t_cpu_percent, cpu_count_real, cpu_count_logical)
  130.  
  131. except Exception, e:
  132. logger.debug(e)
  133. return (False, 0, 0, 0, 0)
  134.  
  135. @log
  136. def __checkProc(self, isparmvalid, proc_cpu_percent, total_cpu_percent, cpu_count_real, cpu_count_logical):
  137.  
  138. try:
  139.  
  140. logger.debug('args => pid:%s, pname:%s, isparmvalid:%s, p_u_percent:%s,p_u_t_percent:%s, t_u_percent:%s, u_r_count:%s, u_l_count:%s'\
  141. , self.monitorproc.pid, self.monitorproc.name(), isparmvalid, proc_cpu_percent, proc_cpu_percent / cpu_count_real, total_cpu_percent, cpu_count_real, cpu_count_logical)
  142.  
  143. if isparmvalid:
  144.  
  145. conf_p_cpu_percent = self.confrules.get('p_cpu_percent', 100)
  146.  
  147. if proc_cpu_percent > conf_p_cpu_percent:
  148. # p.send_signal(signal.SIGTERM)
  149. logger.info('judge=> proc_cpu_percent[%s] > conf_p_cpu_percent[%s]. Now kill %s %s ', proc_cpu_percent, conf_p_cpu_percent, self.monitorproc.pid, self.monitorproc.name())
  150. self.monitorproc.terminate()
  151. else:
  152. logger.info('judge=> proc_cpu_percent[%s] < conf_p_cpu_percent[%s]. Keep Watch %s %s ', proc_cpu_percent, conf_p_cpu_percent, self.monitorproc.pid, self.monitorproc.name())
  153.  
  154. except Exception, e:
  155. logger.debug(e)
  156.  
  157. if __name__ == '__main__':
  158.  
  159. try:
  160. m = Monitor()
  161. m.loopControl()
  162.  
  163. except Exception, e:
  164. logger.debug(e)

MyProcMonitor

日志:

  1. #! /usr/bin/env python
  2. # coding=utf-8
  3.  
  4. import logging
  5. import logging.handlers
  6.  
  7. # NOTSET < DEBUG < INFO < WARNING < ERROR < CRITICAL
  8. # CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET
  9.  
  10. # logging初始化工作
  11. # logging.basicConfig()
  12.  
  13. # create logger
  14. logger = logging.getLogger('tst')
  15. logger.setLevel(logging.DEBUG)
  16.  
  17. # create console handler and set level to debug
  18. consolehandler = logging.StreamHandler()
  19. consolehandler.setLevel(logging.INFO)
  20.  
  21. # filehandler = logging.handlers.RotatingFileHandler('run.log', maxBytes=1024 * 1024, backupCount=5)
  22. filehandler = logging.handlers.TimedRotatingFileHandler('run', when='H', interval=1, backupCount=1)
  23. filehandler.suffix = "%Y%m%d-%H%M.log"
  24. filehandler.setLevel(logging.DEBUG)
  25.  
  26. # create formatter
  27. formatter = logging.Formatter('%(asctime)s - %(message)s')
  28.  
  29. # add formatter to handler
  30. consolehandler.setFormatter(formatter)
  31. filehandler.setFormatter(formatter) # 为handler添加formatter
  32.  
  33. # add handler to logger
  34. logger.addHandler(consolehandler)
  35. logger.addHandler(filehandler)

pylog

Python进程监控-MyProcMonitor的更多相关文章

  1. 【321】python进程监控:psutil

    参考:Python进程监控-MyProcMonitor 参考:Python3.6 安装psutil 模块和功能简介 参考:psutil module (Download files) 参考:廖雪峰 - ...

  2. linux 进程监控

    linux 进程监控 supervise Supervise是daemontools的一个工具,可以用来监控管理unix下的应用程序运行情况,在应用程序出现异常时,supervise可以重新启动指定程 ...

  3. python进程池剖析(一)

    python中两个常用来处理进程的模块分别是subprocess和multiprocessing,其中subprocess通常用于执行外部程序,比如一些第三方应用程序,而不是Python程序.如果需要 ...

  4. Mac下Supervisor进程监控管理工具的安装与配置

    Supervisor是一个类 unix 操作系统下的进程监控管理工具. Supervisor是由 Python 写成,可用 Python 的包安装管理工具 pip(Python Package Ind ...

  5. python系统监控及邮件发送

    python系统监控及邮件发送   #psutil模块是一个跨平台库,能轻松实现获取系统运行的进程和系统利用率   import psutil                              ...

  6. python——进程基础

    我们现在都知道python的多线程是个坑了,那么多进程在这个时候就变得很必要了.多进程实现了多CPU的利用,效率简直棒棒哒~~~ 拥有一个多进程程序: #!/usr/bin/env python #- ...

  7. 【SFTP】使用Jsch实现Sftp文件下载-支持断点续传和进程监控

    参考上篇文章: <[SFTP]使用Jsch实现Sftp文件下载-支持断点续传和进程监控>:http://www.cnblogs.com/ssslinppp/p/6248763.html  ...

  8. python多线程监控指定目录

    import win32file import tempfile import threading import win32con import os dirs=["C:\\WINDOWS\ ...

  9. 使用gdb调试Python进程

    使用gdb调试Python进程 有时我们会想调试一个正在运行的Python进程,或者一个Python进程的coredump.例如现在遇到一个mod_wsgi的进程僵死了,不接受请求,想看看究竟是运行到 ...

随机推荐

  1. BZOJ1013 JSOI2008 球形空间产生器sphere 【高斯消元】

    BZOJ1013 JSOI2008 球形空间产生器sphere Description 有一个球形空间产生器能够在n维空间中产生一个坚硬的球体.现在,你被困在了这个n维球体中,你只知道球面上n+1个点 ...

  2. 防范DDoS攻击的几种方式

    一.拒绝服务攻击的发展: 从拒绝服务攻击诞生到现在已经有了很多的发展,从最初的简单Dos到现在的DdoS.那么什么是Dos和DdoS呢?DoS是一种利用单台计算机的攻击 方式.而DdoS(Distri ...

  3. Sprint第一个冲刺(第八天)

    一.Sprint介绍 完善点餐界面,点击进行跳转. 实验截图: 任务进度: 二.Sprint周期 看板: 燃尽图:

  4. ASP.NET性能优化原则

    从哪些方面对asp.net进行性能优化,本文作了详细的阐述,希望对大家有所帮助. 一.SqlDataRead和Dataset的选择Sqldataread优点:读取数据非常快.如果对返回的数据不需做大量 ...

  5. VS 2013 简体中文 专业版 下载地址。

    官方原始链接:http://download.microsoft.com/download/7/A/C/7AC27F37-FDFE-4991-B18A-962E26E31BD1/VS2013_RTM_ ...

  6. python模块--随机模块

    import random print(random.random()) # 随机产生一个(0,1)的 float 0.026244299361600776 print(random.randint( ...

  7. nginx grpc 试用

    1. 编译 wget https://nginx.org/download/nginx-1.13.10.tar.gz tar xvf nginx-1.13.10.tar.gz cd nginx-1.1 ...

  8. Mybatis新增返回主键的两种方法 (mysql)

    1.自增:LAST_INSERT_ID (自动返回最后一个INSERT或 UPDATE 问询为 AUTO_INCREMENT列设置的第一个 发生的值.) <!-- mysql的自增ID :LAS ...

  9. Linux 之 hugepage 大页内存理论

    HugePages是通过使用大页内存来取代传统的4kb内存页面,使得管理虚拟地址数变少,加快了从虚拟地址到物理地址的映射以及通过摒弃内存页面的换入换出以提高内存的整体性能.尤其是对于8GB以上的内存以 ...

  10. 561. 数组拆分 I

    题目 python class Solution: def arrayPairSum(self, nums): """ :type nums: List[int] :rt ...