python hands-on script-timed detection of unresponsive processes and restart

Keywords: Session Windows

background

There are always some programs in the windows platform performance is not stable, no response for a period of time, but have to use, each time is found a problem to restart manually, now write a script to check whether the process is normal, automatically restart.

Knowledge Points

  1. schedule Timing Task Scheduling

  2. os.popen runs the program and reads the parsed results

Code decomposition

Script main entry
if __name__ == '__main__':
    #Check every 5 seconds
    schedule.every(5).seconds.do(check_job)
    #Fixed here means that every second schedule s to see if there is a pending task, and then executes it.
    while True:
        schedule.run_pending()
        time.sleep(1)
Other examples of schedule
import schedule
import time

def job(message='stuff'):
    print("I'm working on:", message)

#Every 10 minutes
schedule.every(10).minutes.do(job)
#Hourly
schedule.every().hour.do(job, message='things')
#10:30 a.m. a day
schedule.every().day.at("10:30").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)
Check unresponsive processes and restart
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')
Find a list of eligible processes
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)
Parse command execution results
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 sample output
Image Name PID Session Name Session # Memory Use
========================= ======== ================ =========== ============
WizChromeProcess.exe          1620 Console                    1     32,572 K

Complete code

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)

Posted by kvishnu_13 on Mon, 22 Apr 2019 00:30:35 -0700