python进程监控

Posted cbreeze

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python进程监控相关的知识,希望对你有一定的参考价值。

 1 # -*- coding:utf-8 -*-
 2 import subprocess,time,sys
 3 import os
 4 os.system("title 监控:自动签到1".decode(UTF-8).encode(GBK))
 5 TIME = 1                       #程序状态检测间隔(单位:分钟)
 6 CMD = "4399.py"                 #需要执行程序的绝对路径,支持jar 如:D:\calc.exe 或者D:\test.jar
 7 
 8 
 9 
10 class Auto_Run():
11     def __init__(self,sleep_time,cmd):
12         self.sleep_time = sleep_time
13         self.cmd = cmd
14         self.ext = (cmd[-3:]).lower()        #判断文件的后缀名,全部换成小写
15         self.p = None                        #self.p为subprocess.Popen()的返回值,初始化为None
16         self.run()                           #启动时先执行一次程序
17 
18         try:
19             while 1:
20                 time.sleep(sleep_time * 6)  #休息10分钟,判断程序状态
21                 self.poll = self.p.poll()    #判断程序进程是否存在,None:表示程序正在运行 其他值:表示程序已退出
22                 if self.poll is None:
23                     print "运行正常".decode(UTF-8).encode(GBK)
24                 else:
25                     print "未检测到程序运行状态,准备启动程序".decode(UTF-8).encode(GBK)
26                     self.run()
27         except KeyboardInterrupt as e:
28             print "检测到CTRL+C,准备退出程序!".decode(UTF-8).encode(GBK)
29 #            self.p.kill()                   #检测到CTRL+C时,kill掉CMD中启动的exe或者jar程序
30 
31     def run(self):
32         if self.ext == ".py":
33             print start OK!
34             self.p = subprocess.Popen([python,%s % self.cmd], stdin = sys.stdin,stdout = sys.stdout, stderr = sys.stderr, shell = False)
35         else:
36             pass
37 app = Auto_Run(TIME,CMD)

 

以上是关于python进程监控的主要内容,如果未能解决你的问题,请参考以下文章