程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

python程序守候-批量监控程序运行,程序意外关闭后自动重启程序

hfteth 2024-12-19 09:13:20 技术文章 18 ℃

最近用python开发了一些程序后跑在一台专门服务器上,部分程序在运行一段时间会莫名地关闭,分析估计是程序遇到一些未知情况导致自动关闭,为了防止出现这个问题,考虑能不能开发个软件,时刻监控批量指定程序的运行,一旦发现进程中没有这个程序,就自动重启这个程序,经过一段时间百度搜索学习借鉴,终于做出来了,本人给程序起名:程序守候。

该程序原理如下:

1、获取指定文件夹所有程序清单和程序路径:

def getFiles(path):
    if path[-1:] != '\\':
        path += '\\'
    path=path+"jivy\\"

    dirFiles = os.listdir(path)

    for file in dirFiles:
        filePath = path + file
        if SUFFIX == '' or file[-4:] == SUFFIX:
            files.append([file,filePath]

2、将程序清单和进程清单进行一一对比,如果进程中没有该程序,就启动该程序

def shouhou(ProcessName,ProgramPath):
    for process in c.Win32_Process():
        ProList.append(str(process.Name))
    if ProcessName in ProList:
        pass
        # 判断进程名是否在进程清单中,如果没有,就重启该程序
    else:
        print(ProcessName +"已停止,正在重新启动服务。。。")
        os.startfile(ProgramPath)
        print("重新启动"+ProcessName +"成功。。。")
        print(time.strftime('%Y-%m-%d %H:%M:%S ', time.localtime()))
    del ProList[:]

启动程序,重复刷新文件夹和进程

if __name__ == '__main__':
    print("程序守候 Design by jivy ")
    print("该程序能自动监护程序目录“jivy”文件夹里面所有程序运行,程序意外中止可自动重启 ")
    while 1:
        ProList = []
        files = []
        try:
            getFiles(PATH)
            for fff in files:
                shouhou(fff[0],fff[1])
            time.sleep(60) #每60秒刷新一次
        except:
            pass


汇总代码如下,供大家学习:

# -*- coding: utf-8 -*-
# Design by jivy
import wmi
import os
import time
ProList = []
c = wmi.WMI()
PATH=os.getcwd()
SUFFIX = '.exe'       #查找.exe文件
files = []
result = []

def getFiles(path):
    if path[-1:] != '\\':
        path += '\\'
    path=path+"jivy\\"

    dirFiles = os.listdir(path)

    for file in dirFiles:
        filePath = path + file
        if SUFFIX == '' or file[-4:] == SUFFIX:
            files.append([file,filePath])

def shouhou(ProcessName,ProgramPath):
    for process in c.Win32_Process():
        ProList.append(str(process.Name))
    if ProcessName in ProList:
        pass
        # 判断进程名是否在进程清单中,如果没有,就重启该程序
    else:
        print(ProcessName +"已停止,正在重新启动服务。。。")
        os.startfile(ProgramPath)
        print("重新启动"+ProcessName +"成功。。。")
        print(time.strftime('%Y-%m-%d %H:%M:%S ', time.localtime()))
    del ProList[:]
if __name__ == '__main__':
    print("程序守候 Design by jivy ")
    print("该程序能自动监护程序目录“jivy”文件夹里面所有程序运行,程序意外中止可自动重启 ")
    while 1:
        ProList = []
        files = []
        try:
            getFiles(PATH)
            for fff in files:
                shouhou(fff[0],fff[1])
            time.sleep(60) #每60秒刷新一次
        except:
            pass

说明:需将py封装成EXE,否则进程中无法识别进程名称。

Tags:

最近发表
标签列表