凌的博客

您现在的位置是: 首页 > 学无止境 > python > 

python

python检查软件是否启动,未启动则开启

2020-04-02 python 2953
import threading
import os
import subprocess
from configparser import ConfigParser


class TaskCheck:
    def __init__(self, task):
        self.task = task
        self.task_name = os.path.basename(task)

    def processCount(self):
        p = os.popen('tasklist /FI "IMAGENAME eq %s"' % self.task_name)
        return p.read().count(self.task_name)

    def timerStart(self):
        t = threading.Timer(10, self.watch_exe)
        t.start()

    def watch_exe(self):
        if self.processCount() < 1:
            print("未启动:%s" % self.task_name)
            print(self.task)
            print(subprocess.Popen(["cmd/c", "start", " ",self.task],shell=True))
        else:
            print("%s is running" % self.task_name)
        task.timerStart()


if __name__ == "__main__":
    cf = ConfigParser()
    cf.read("./exe.ini", encoding="utf-8")
    exe_file = cf.get("settings", "file")

    # exe_file = r"D:\Program Files (x86)\test v1.0\test\test.exe"
    task = TaskCheck(exe_file)
    task.watch_exe()
    
    
########################################################################################
import time
import os
import subprocess
from configparser import ConfigParser
import re


class TaskCheck:
    task_index = 0

    def __init__(self, task):
        self.task = task
        self.task_name = os.path.basename(task)

    # def processCount(self):
    #     p = os.popen('tasklist /FI "IMAGENAME eq %s"' % self.task_name)
    #     return p.read().count(self.task_name)

    def timerStart(self):

        while True:
            if self.task_index > 10:
                os.system("cls")
                self.task_index = 0

            print("等待10秒后检查:%s" % self.task_name)
            self.watch_exe()
            time.sleep(10)

            self.task_index += 1

    def closeExe(self):
        subprocess.Popen(["taskkill", "/f", "/im", self.task_name])

    def killProcessID(self, id):
        subprocess.Popen("taskkill /PID {0}".format(id))

    def processIDs(self):
        # cmd_str = "tasklist | findstr /i {0}".format(self.task_name)
        cmd_str = 'tasklist /FI "IMAGENAME eq {0}"'.format( self.task_name)

        p = subprocess.Popen(cmd_str, stdout=subprocess.PIPE, bufsize=1, shell=True)
        info = ""
        for line in iter(p.stdout.readline, b''):
            info += line.decode('gbk', 'ignore')
        p.stdout.close()
        p.wait()
        ids = []

        for line in info.split("\n"):
            try:
                m = re.search("(\d+)\sConsole", line, re.I)
            except Exception as e:
                print("Error:%s" % str(e))
            if m is not None:
                ids.append(int(m[1]))

        return ids

    def watch_exe(self):
        ids = self.processIDs()
        total = len(ids)
        if total < 1:
            print("未启动:%s" % self.task_name)
            print(self.task)
            print(subprocess.Popen(["cmd/c", "start", " ", self.task], shell=True))
        else:
            if total == 1:
                print("%s is running" % self.task_name)
            else:
                print("开启的软件个数为:%d" % total)
                # print("关闭软件,等待重启")
                # self.closeExe()
                ids.sort(reverse=True)
                # 关闭第一个
                self.killProcessID(ids[0])


if __name__ == "__main__":
    cf = ConfigParser()
    cf.read("./exe.ini", encoding="utf-8")
    exe_file = cf.get("settings", "file")

    # exe_file = r"D:\Program Files (x86)\test v1.0\test\test.exe"
    task = TaskCheck(exe_file)
    task.timerStart()
    #task.processIDs()
    
########################################
# 本人经过多番测试,最终使用的
# 检查软件是否在运行 没有则 开启
import time
import os
import subprocess
from configparser import ConfigParser
import re


class TaskCheck:
    task_index = 0

    def __init__(self, task):
        self.task = task
        self.task_name = os.path.basename(task)

    def processCount(self):
        p = os.popen('tasklist /FI "IMAGENAME eq %s"' % self.task_name)
        return p.read().count(self.task_name)

    def timerStart(self):

        while True:
            if self.task_index > 10:
                os.system("cls")
                self.task_index = 0

            print("等待10秒后检查:%s" % self.task_name)
            self.watch_exe()
            time.sleep(10)

            self.task_index += 1

    def closeExe(self):
        subprocess.Popen(["taskkill", "/f", "/im", self.task_name])

    def killProcessID(self, id):
        subprocess.Popen("taskkill /PID {0}".format(id))

    def processIDs(self):
        # cmd_str = "tasklist | findstr /i {0}".format(self.task_name)
        cmd_str = 'tasklist /FI "IMAGENAME eq {0}"'.format(self.task_name)
        # print(cmd_str)
        p = subprocess.Popen(cmd_str, stdout=subprocess.PIPE, bufsize=1, shell=True)
        info = ""
        for line in iter(p.stdout.readline, b''):
            info += line.decode('gbk', 'ignore')
        p.stdout.close()
        p.wait()
        ids = []
        # print(info)
        for line in info.split("\n"):
            try:
                m = re.search("(\d+)\sConsole", line, re.I)
            except Exception as e:
                print("Error:%s" % str(e))
            if m is not None:
                ids.append(int(m[1]))
        # print(ids)
        return ids

    def watch_exe(self):
        total = self.processCount()
        if total < 1:
            self.closeExe()
            print("5秒后启动")
            time.sleep(5)
            print("未启动:%s" % self.task_name)
            print(self.task)
            print(subprocess.Popen(["cmd/c", "start", " ", self.task], shell=True))
        else:

            # if total > 1:
            #     print("开启的软件个数为:%d" % total)
            #     # self.closeExe()
            #     ids.sort(reverse=True)
            #     # 关闭第一个
            #     print("关闭软件")
            #     self.killProcessID(ids[0])
            # else:
            print("%s is running" % self.task_name)


if __name__ == "__main__":
    cf = ConfigParser()
    cf.read("./exe.ini", encoding="utf-8")
    exe_file = cf.get("settings", "file")

    # exe_file = r"D:\Program Files (x86)\test v1.0\test\test.exe"
    task = TaskCheck(exe_file)
    task.timerStart()
    # task.processIDs()
    # input("enter test..")


文章评论

0条评论