0
点赞
收藏
分享

微信扫一扫

python 根据绝对路径关闭进程

import os
import psutil

# 如果未知路径且写入了配置环境
# os.system("taskkill /f /im excel.exe & taskkill /f /im wps.exe")
# cmd taskkill 直接输入 不需加双引号
# cmd taskkill 无法根据绝对路径关闭程序 无论有没有双引号(无效查询 或 没有找到进程)

# True, False, None(未成功执行, 不存在)
# 此种for循环, 不能else return
# pid 进程id
# 信号编号==9 强制结束
def fun_kill(path):
    if os.path.exists(path):
        for proc in psutil.process_iter(['pid', 'name', 'exe']):
            if proc.info['exe'] == path:
                print(proc)
                print(path, "has been found, pid:", proc.info['pid'])
                os.kill(proc.info['pid'], 9)
                print(path, "process has been killed, pid:", proc.info['pid'])
                return True
        print(path, "is not running")
        return False
    else:
        print(path, "does not exist")
        return None

fun_kill(path)

举报

相关推荐

0 条评论