背景
總有一些程序在windows平臺(tái)表現(xiàn)不穩(wěn)定,動(dòng)不動(dòng)一段時(shí)間就無(wú)響應(yīng),但又不得不用,每次都是發(fā)現(xiàn)問(wèn)題了手動(dòng)重啟,現(xiàn)在寫(xiě)個(gè)腳本定時(shí)檢測(cè)進(jìn)程是否正常,自動(dòng)重啟。
涉及知識(shí)點(diǎn)
schedule定時(shí)任務(wù)調(diào)度
os.popen運(yùn)行程序并讀取解析運(yùn)行結(jié)果
代碼分解
腳本主入口
if __name__ == '__main__':
#每5秒執(zhí)行檢查任務(wù)
schedule.every(5).seconds.do(check_job)
#此處固定寫(xiě)法,意思是每秒鐘schedule看下是否有pending的任務(wù),有就執(zhí)行
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)
#每小時(shí)
schedule.every().hour.do(job, message='things')
#每天10點(diǎn)30分
schedule.every().day.at("10:30").do(job)
while True:
schedule.run_pending()
time.sleep(1)
檢查無(wú)響應(yīng)進(jìn)程并重啟
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')
}
查找符合條件的進(jìn)程列表
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)
解析命令執(zhí)行結(jié)果
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 會(huì)話名 會(huì)話# 內(nèi)存使用
========================= ======== ================ =========== ============
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)