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


Posted in Python onApril 22, 2019

总有一些程序在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批量替换多文件字符串问题详解
Apr 22 Python
使用EduBlock轻松学习Python编程
Oct 08 Python
Python对象与引用的介绍
Jan 24 Python
Python 分享10个PyCharm技巧
Jul 13 Python
python scrapy爬虫代码及填坑
Aug 12 Python
python实现最大优先队列
Aug 29 Python
Django实现文件上传和下载功能
Oct 06 Python
python模块导入的方法
Oct 24 Python
用 Python 制作地球仪的方法
Apr 24 Python
如何对python的字典进行排序
Jun 19 Python
Python使用urlretrieve实现直接远程下载图片的示例代码
Aug 17 Python
python树莓派通过队列实现进程交互的程序分析
Jul 04 Python
django query模块
Apr 20 #Python
不到20行代码用Python做一个智能聊天机器人
Apr 19 #Python
详解Python3 基本数据类型
Apr 19 #Python
python面向对象法实现图书管理系统
Apr 19 #Python
python远程连接MySQL数据库
Apr 19 #Python
详解Python匿名函数(lambda函数)
Apr 19 #Python
解决python3中的requests解析中文页面出现乱码问题
Apr 19 #Python
You might like
图片存储与浏览一例(Linux+Apache+PHP+MySQL)
2006/10/09 PHP
php实现遍历目录并删除指定文件中指定内容
2015/01/21 PHP
PHPCMS忘记后台密码的解决办法
2016/10/30 PHP
Laravel学习教程之View模块详解
2017/09/18 PHP
实现php删除链表中重复的结点
2018/09/27 PHP
jQuery方法简洁实现隔行换色及toggleClass的使用
2013/03/15 Javascript
Node.js异步I/O学习笔记
2014/11/04 Javascript
详解照片瀑布流效果(js,jquery分别实现与知识点总结)
2017/01/01 Javascript
Chrome调试折腾记之JS断点调试技巧
2017/09/11 Javascript
setTimeout时间设置为0详细解析
2018/03/13 Javascript
JavaScript中为事件指定处理程序的五种方式分析
2018/07/27 Javascript
深入Vue-Router路由嵌套理解
2018/08/13 Javascript
[02:48]DOTA2英雄基础教程 拉席克
2013/12/12 DOTA
[00:38]TI珍贵瞬间系列(二):笑
2020/08/26 DOTA
[56:38]DOTA2-DPC中国联赛正赛Aster vs Magma BO3 第一场 3月5日
2021/03/11 DOTA
python计算圆周长、面积、球体体积并画出圆
2014/04/08 Python
在Python中使用SimpleParse模块进行解析的教程
2015/04/11 Python
Python配置文件解析模块ConfigParser使用实例
2015/04/13 Python
Python的requests网络编程包使用教程
2016/07/11 Python
python 3利用Dlib 19.7实现摄像头人脸检测特征点标定
2018/02/26 Python
python更新数据库中某个字段的数据(方法详解)
2020/11/18 Python
用python 绘制茎叶图和复合饼图
2021/02/26 Python
CSS Grid布局教程之网格单元格布局
2014/12/30 HTML / CSS
html5 input输入实时检测以及延时优化
2018/07/18 HTML / CSS
美国花布包包品牌:Vera Bradley
2017/08/11 全球购物
thinkphp5 redis缓存新增方法实例讲解
2021/03/24 PHP
环境科学专业个人求职信
2013/09/26 职场文书
年终自我鉴定
2013/10/09 职场文书
小学生红领巾广播稿
2014/01/21 职场文书
2014年两会学习心得体会
2014/03/10 职场文书
艺术节主持词
2014/04/02 职场文书
电教室标语
2014/06/20 职场文书
三傻大闹宝莱坞观后感
2015/06/03 职场文书
七年级之开学家长寄语35句
2019/09/05 职场文书
浅谈spring boot使用thymeleaf版本的问题
2021/08/04 Java/Android
《废话连篇——致新手》——chinapizza
2022/04/05 无线电