小工具知识网

当前位置: 首页 > 行业知识 > 用python写一个自动进程守护,带UI

行业知识

用python写一个自动进程守护,带UI

2026-11-09 03:27:09 来源:互联网转载

功能���指定程序关闭后自动重启,并点击1作为启动

原来的想法是群成员说的某软件打包后,软件进程被杀后,界面白屏。所以写了个计算器重启demo进行进程守护

import subprocessimport timeimport pyautoguiimport psutil#用计算器做演示。def is_calculator_running():    # 查找所有正在运行的计算器进程    for proc in psutil.process_iter(['pid', 'name']):        # 检查进程名是否为 'Calculator.exe'        if proc.info['name'] == 'Calculator.exe':            return True    return Falsedef open_calculator():    # 启动计算器进程    process = subprocess.Popen('calc.exe')    return processdef click_button_1():    # 等待计算器打开并加载    time.sleep(2)  # 根据需要调整等待时间    # 模拟点击"1"按钮,这里直接发送"1"键    # 注意:确保计算器是当前激活的窗口    pyautogui.press('1')def main():    while True:        if not is_calculator_running():            print("Calculator is not running. Starting...")            process = open_calculator()            click_button_1()        time.sleep(1)  # 每秒检查一次if __name__ == '__main__':    main()

带UI的

,代码没有优化,能用就行

#!/usr/bin/env python3#-*- coding:utf-8 -*-import sysimport timeimport threadingimport subprocessimport pyautoguiimport psutilimport tkinter as tk#用计算器做演示。import sysfrom tkinter import *from tkinter.font import Fontfrom tkinter.ttk import *#Usage:showinfo/warning/error,askquestion/okcancel/yesno/retrycancelfrom tkinter.messagebox import *#from tkinter import filedialog  #.askopenfilename()#from tkinter import simpledialog  #.askstring()class Application_ui(Frame):    #这个类仅实现界面生成功能,具体事件处理代码在子类Application中。    def __init__(self, master=None):        super().__init__(master)        # To center the window on the screen.        ws = self.master.winfo_screenwidth()        hs = self.master.winfo_screenheight()        x = (ws / 2) - (333 / 2)        y = (hs / 2) - (271 / 2)        self.master.geometry('%dx%d+%d+%d' % (333,271,x,y))        self.master.title('Form1')        self.createWidgets()    def createWidgets(self):        self.top = self.winfo_toplevel()        self.style = Style()        self.Command2Var = StringVar(value='强制停止本程序')        self.style.configure('TCommand2.TButton', font=('宋体',9))        self.Command2 = Button(self.top, text='强制停止本程序', textvariable=self.Command2Var, command=self.Command2_Cmd, style='TCommand2.TButton')        self.Command2.setText = lambda x: self.Command2Var.set(x)        self.Command2.text = lambda : self.Command2Var.get()        self.Command2.place(relx=0.505, rely=0.472, relwidth=0.363, relheight=0.151)        self.Command1Var = StringVar(value='启动监控')        self.style.configure('TCommand1.TButton', font=('宋体',9))        self.Command1 = Button(self.top, text='启动监控', textvariable=self.Command1Var, command=self.Command1_Cmd, style='TCommand1.TButton')        self.Command1.setText = lambda x: self.Command1Var.set(x)        self.Command1.text = lambda : self.Command1Var.get()        self.Command1.place(relx=0.12, rely=0.472, relwidth=0.267, relheight=0.151)        self.Text2Var = StringVar(value='calc.exe')        self.Text2 = Entry(self.top, textvariable=self.Text2Var, font=('宋体',9))        self.Text2.setText = lambda x: self.Text2Var.set(x)        self.Text2.text = lambda : self.Text2Var.get()        self.Text2.place(relx=0.505, rely=0.295, relwidth=0.459, relheight=0.122)        self.Text1Var = StringVar(value='Calculator.exe')        self.Text1 = Entry(self.top, textvariable=self.Text1Var, font=('宋体',9))        self.Text1.setText = lambda x: self.Text1Var.set(x)        self.Text1.text = lambda : self.Text1Var.get()        self.Text1.place(relx=0.505, rely=0.089, relwidth=0.459, relheight=0.151)        self.Label5Var = StringVar(value='比如D:\D1\ajide.exe')        self.style.configure('TLabel5.TLabel', anchor='w', font=('宋体',9))        self.Label5 = Label(self.top, text='比如D:\D1\ajide.exe', textvariable=self.Label5Var, style='TLabel5.TLabel')        self.Label5.setText = lambda x: self.Label5Var.set(x)        self.Label5.text = lambda : self.Label5Var.get()        self.Label5.place(relx=0.048, rely=0.915, relwidth=0.7, relheight=0.092)        self.Label4Var = StringVar(value='名字为Calculator.exe,启动程序是启动路径,')        self.style.configure('TLabel4.TLabel', anchor='w', font=('宋体',9))        self.Label4 = Label(self.top, text='名字为Calculator.exe,启动程序是启动路径,', textvariable=self.Label4Var, style='TLabel4.TLabel')        self.Label4.setText = lambda x: self.Label4Var.set(x)        self.Label4.text = lambda : self.Label4Var.get()        self.Label4.place(relx=0.048, rely=0.797, relwidth=0.988, relheight=0.092)        self.Label3Var = StringVar(value='保护对象是在任务管理器的名字,如计算器,')        self.style.configure('TLabel3.TLabel', anchor='w', font=('宋体',9))        self.Label3 = Label(self.top, text='保护对象是在任务管理器的名字,如计算器,', textvariable=self.Label3Var, style='TLabel3.TLabel')        self.Label3.setText = lambda x: self.Label3Var.set(x)        self.Label3.text = lambda : self.Label3Var.get()        self.Label3.place(relx=0.048, rely=0.679, relwidth=0.844, relheight=0.151)        self.Label2Var = StringVar(value='如监控到关闭启动程序')        self.style.configure('TLabel2.TLabel', anchor='w', font=('宋体',9))        self.Label2 = Label(self.top, text='如监控到关闭启动程序', textvariable=self.Label2Var, style='TLabel2.TLabel')        self.Label2.setText = lambda x: self.Label2Var.set(x)        self.Label2.text = lambda : self.Label2Var.get()        self.Label2.place(relx=0.048, rely=0.266, relwidth=0.363, relheight=0.122)        self.Label1Var = StringVar(value='请输入你要保护的对象')        self.style.configure('TLabel1.TLabel', anchor='w', font=('宋体',9))        self.Label1 = Label(self.top, text='请输入你要保护的对象', textvariable=self.Label1Var, style='TLabel1.TLabel')        self.Label1.setText = lambda x: self.Label1Var.set(x)        self.Label1.text = lambda : self.Label1Var.get()        self.Label1.place(relx=0.048, rely=0.118, relwidth=0.411, relheight=0.092)class Application(Application_ui):    #这个类实现具体的事件处理回调函数。界面生成代码在Application_ui中。    def __init__(self, master=None):        super().__init__(master)    def Command2_Cmd(self, event=None):        #TODO, Please finish the function here!        input_value = self.Text2.text()         print(input_value)                time.sleep(100)        # 执行一些任务...# 关闭可执行文件        sys.exit()        pass    def Command1_Cmd(self, event=None):        #TODO, Please finish the function here!        text1 = self.Text1.text()        text2 = self.Text2.text()        def is_calculator_running():            # 查找所有正在运行的计算器进程            for proc in psutil.process_iter(['pid', 'name']):                # 检查进程名是否为 'Calculator.exe'                if proc.info['name'] == text1:                    return True            return False        def open_calculator():            # 启动计算器进程            process = subprocess.Popen(text2)            return process        def click_button_1():            # 等待计算器打开并加载            time.sleep(2)  # 根据需要调整等待时间            # 模拟点击"1"按钮,这里直接发送"1"键            # 注意:确保计算器是当前激活的窗口            pyautogui.press('1')        def main1():            while True:                if not is_calculator_running():                    print("Calculator is not running. Starting...")                    process = open_calculator()                    click_button_1()                time.sleep(1)  # 每秒检查一次        def long_running_task():    # 模拟一个耗时的任务         main1()    # 创建并启动线程        thread = threading.Thread(target=long_running_task)        thread.start()                                       passif __name__ == "__main__":    top = Tk()    Application(top).mainloop()

上一篇:服务器怎么调出软件库数据?

下一篇:怎么用cms建站?