python监控进程并实现掉线重启
生活随笔
收集整理的這篇文章主要介紹了
python监控进程并实现掉线重启
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
分析了具體思路:
1.做個線程定時器,每隔2s執(zhí)行系統(tǒng)命令查詢指定進(jìn)程名稱是否存在
2.如果不存在,就重啟;不存在就不進(jìn)行后續(xù)的操作。
相關(guān)代碼(以迅雷為例):
import datetime import os import subprocessfrom threading import Timerdef restart_process(process_name):red = subprocess.Popen('tasklist', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)tasklist_str = red.stdout.read().decode(encoding='gbk')re_path = process_name.split("\\")[-1]formattime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')if re_path not in tasklist_str:# obj = connect_emai()# sendmail('程序卡掉正在重啟。。。', obj)# 發(fā)送HTTP請求# url = "http://159.138.131.148/server_offline.html"# request = urllib.request(url)global countcount += 1print(formattime + '第' + str(count) + '次檢測發(fā)現(xiàn)異常重連')cmd = process_nameos.system(process_name)# res = subprocess.Popen(cmd,stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True)# print(res.stderr.read().decode(encoding='gbk'),res.stdout.read().decode(encoding='gbk'))# sendmail('重啟連接成功!',obj)print('yes,connected')else:global error_counterror_count += 1print(formattime + '第' + str(error_count) + '次檢測正在運(yùn)行中')global timertimer = Timer(2, restart_process, ("start F:\Thunder\Program\Thunder.exe",))timer.start()count = 0 error_count = 0 timer = Timer(2, restart_process, ("start F:\Thunder\Program\ThunderStart.exe",)) timer.start()如果CPU一直維持在80%以上 就主動殺死進(jìn)程,并重啟進(jìn)程,使用了牛逼的psutil 跨系統(tǒng)平臺操作庫。實(shí)現(xiàn)代碼
其他遠(yuǎn)程啟動等騷操作:https://www.cnblogs.com/my-python-2019/p/11177224.html
總結(jié)
以上是生活随笔為你收集整理的python监控进程并实现掉线重启的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VS2017读取ini 文件中文乱码
- 下一篇: python:文件路径多级获取