# 根据pid进行守护,先保存一个pid import time import os class Demo: def __init__(self): pass def setpid(self): # 记录进程号PID fo = open("pid.txt", "w") pid = str(os.getpid()) print("pid", pid) fo.write(pid) fo.flush() fo.close() return pid def execute(self): pid = self.setpid() print("启动程序,进程号:" + str(pid)) i = 1 while True: print("pid = " + pid + " ---------- run " + str(i) + " s ") time.sleep(1) i += 1 if i > 10: break print("程序关闭...") if __name__ == '__main__': demo = Demo() demo.execute()
#读取pid再进行判断 import psutil import os class Monitor: pidNotHandle = [] def __init__(self): self.pidNotHandle = list(psutil.process_iter()) # 获取当前计算机的pid def getpid(self): # 获取进程号PID fo = open("pid_.txt", "r") result = fo.read() fo.flush() fo.close() return result def execute(self): pid = [] for each in self.pidNotHandle: a = str(each) # each 是 class类型,可用type(each)查看类型 # a 数据样式为:psutil.Process(pid=0, name='System Idle Process') pid.append(a[15:-1]) # 只取括号内部分;pid=0, name='System Idle Process' status = 0 # 被监控程序进程存在状态,0不存在,1存在 for each in pid: nameposition = each.find("name") # 获取name的位置;name='System Idle Process' namevalue = each[nameposition + 6:-1] # 获取name值;System Idle Process pidposition = each.find("pid") pidvalue = each[pidposition + 4:nameposition - 2] print("name=" + namevalue + ", pid=" + pidvalue + "\n") if pidvalue == self.getpid(): status = 1 print("发现进程==============name=" + namevalue + ", pid=" + pidvalue + "\n") break if status == 0: # 进程不存在,重新启动程序 cmd = r"python test1.py" print(cmd) res = os.popen(cmd) print(res) print("重启程序.............") print("ending.............") return 0 if __name__ == '__main__': Monitor().execute()
# 如果是打包成exe的程序 import time import sys import psutil import os class MonitorServer: pidNotHandle = [] servername = "jira_Scheduler.exe" def __init__(self): self.pidNotHandle = list(psutil.process_iter()) def execute(self): pid = [] for each in self.pidNotHandle: a = str(each) pid.append(a[15:-1]) status = 0 for each in pid: nameposition = each.find("name") namevalue = each[nameposition + 6:-1].split(',')[0].replace("'","") pidposition = each.find("pid") pidvalue = each[pidposition + 4:nameposition - 2] print("name=" + namevalue + ", pid=" + pidvalue + "\n") if namevalue == self.servername: status = 1 print("发现进程==============name=" + namevalue + ", pid=" + pidvalue + "\n") break if status == 0: #如果需要重新调用exe程序,此处为在同一个路径下,且将此程序也打包为exe程序时,需要切换真实的工作路径 #如果此程序不打包,拼接此时的运行路径即可 print(os.path.join(os.path.dirname(os.path.realpath(sys.executable)), self.servername)) cmd = os.path.join(os.path.dirname(os.path.realpath(sys.executable)), self.servername) print(cmd) os.popen(cmd) time.sleep(5) print("重启程序.............") print("ending.............") return 0 if __name__ == '__main__': MonitorServer().execute()