python定时检测无响应进程并重启的实例代码

yipeiwu_com5年前Python基础

总有一些程序在windows平台表现不稳定,动不动一段时间就无响应,但又不得不用,每次都是发现问题了手动重启,现在写个脚本定时检测进程是否正常,自动重启。

涉及知识点

  1. schedule定时任务调度
  2. os.popen运行程序并读取解析运行结果

代码分解

脚本主入口

if __name__ == '__main__':
  #每5秒执行检查任务
  schedule.every(5).seconds.do(check_job)
  #此处固定写法,意思是每秒钟schedule看下是否有pending的任务,有就执行
  while True:
    schedule.run_pending()
    time.sleep(1)

schedule的其它示例

import schedule
import time
def job(message='stuff'):
  print("I'm working on:", message)
#每10分钟
schedule.every(10).minutes.do(job)
#每小时
schedule.every().hour.do(job, message='things')
#每天10点30分
schedule.every().day.at("10:30").do(job)
while True:
  schedule.run_pending()
  time.sleep(1)

检查无响应进程并重启

def check_job():
  process_name = "xx.exe"
  not_respond_list = list_not_response(process_name)
  if len(not_respond_list) <= 0:
    return
  pid_params = " ".join(["/PID " + pid for pid in not_respond_list])
  os.popen("taskkill /F " + pid_params)
  if len(list_process(process_name)) <= 0:
    start_program(r'E:\xx\xx.exe')
}

查找符合条件的进程列表

def list_process(process_name, not_respond=False):
  cmd = 'tasklist /FI "IMAGENAME eq %s"'
  if not_respond:
    cmd = cmd + ' /FI "STATUS eq Not Responding"'
  output = os.popen(cmd % process_name)
  return parse_output(output.read())
def list_not_response(process_name):
  return list_process(process_name, True)

解析命令执行结果

def parse_output(output):
  print(output)
  pid_list = []
  lines = output.strip().split("\n")
  if len(lines) > 2:
    for line in lines[2:]:
      pid_list.append(line.split()[1])
  return pid_list

tasklist示例输出

映像名称            PID 会话名       会话#    内存使用
========================= ======== ================ =========== ============
WizChromeProcess.exe     1620 Console          1   32,572 K

完整代码

import os
import time
import schedule
def parse_output(output):
  print(output)
  pid_list = []
  lines = output.strip().split("\n")
  if len(lines) > 2:
    for line in lines[2:]:
      pid_list.append(line.split()[1])
  return pid_list
def list_not_response(process_name):
  return list_process(process_name, True)
def list_process(process_name, not_respond=False):
  cmd = 'tasklist /FI "IMAGENAME eq %s"'
  if not_respond:
    cmd = cmd + ' /FI "STATUS eq Not Responding"'
  output = os.popen(cmd % process_name)
  return parse_output(output.read())
def start_program(program):
  os.popen(program)
def check_job():
  process_name = "xx.exe"
  not_respond_list = list_not_response(process_name)
  if len(not_respond_list) <= 0:
    return
  pid_params = " ".join(["/PID " + pid for pid in not_respond_list])
  os.popen("taskkill /F " + pid_params)
  if len(list_process(process_name)) <= 0:
    start_program(r'E:\xxx\xx.exe')
if __name__ == '__main__':
  schedule.every(5).seconds.do(check_job)
  while True:
    schedule.run_pending()
    time.sleep(1)

总结

以上所述是小编给大家介绍的python定时检测无响应进程并重启的实例代码 ,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

python WindowsError的错误代码详解

WindowsError的错误代码详解 0操作成功完成。 1功能错误。 2系统找不到指定的文件。 3系统找不到指定的路径。 4系统无法打开文件。 5拒绝访问。 6句柄无效。 7存储控制块...

下载官网python并安装的步骤详解

下载官网python并安装的步骤详解

怎么下载官网python并安装? Python火了起来,很多人开始学习起来了,那么Python安装包,去哪里下载呢。那当然是去官网咯。 Python官网或直接 访问 https://ww...

python实现的重启关机程序实例

本文实例讲述了Python实现的重启关机程序的方法,对Python程序设计有一定的参考价值。具体方法如下: 实例代码如下: #!/usr/bin/python #coding=utf...

python实现简单的计时器功能函数

本文实例讲述了python实现简单的计时器功能函数。分享给大家供大家参考。具体如下: 此函数通过python实现了一个简单的计时器动能: ''' Simple Timing Func...

Python3.7实现中控考勤机自动连接

由于考勤机与OA对接,OA会在每天定时取考勤机数据,但是需要考勤机是连接状态,所以搜索了下相关教程,写了个脚本自动连接。完全是个Python小白,代码烂,仅作为笔记。 理论上支持所有程序...