常用函数utils

结束Windows进程

import psutil
def process_kill(process_name):
    for proc in psutil.process_iter():
        try:
            # 获取进程信息
            process_info = proc.as_dict(attrs=['pid', 'name'])
            pid = process_info['pid']
            name = process_info['name']

            # 根据进程名进行匹配并杀死进程
            if name.lower() == process_name.lower():
                proc.kill()
                print(f"Process '{name}' with PID {pid} has been killed.")
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass

释放端口

import os

def release_port(port_number):
    try:
        # 使用 netstat 命令查找占用指定端口的进程
        result = os.popen(f"netstat -ano | findstr :{port_number}").read()

        # 获取进程的 PID
        pid = result.strip().split()[-1]

        if pid.isdigit():
            pid = int(pid)

            # 使用 taskkill 命令终止占用该端口的进程
            os.system(f"taskkill /F /PID {pid}")
            print(f"Port {port_number} has been released.")
        else:
            print(f"No process is using port {port_number}.")
    except Exception as e:
        print(f"Error: {e}")

启动Windows进程

from pywinauto import Application


def StartProcess():
    Application().start(r"D:\CET\Common\ConfigServer.exe")
    # time.sleep(30)
    Application().start(r"D:\CET\Common\FrontSC.exe")
    Application().start(r"D:\CET\Common\PecService.exe")

你可能感兴趣的:(后端自动化,python)