python 杀死进程

code
def kill_process_by_pid(pid,process_name):
    print(f"正在尝试结束 {process_name} 进程...")
    subprocess.call(['taskkill','/F','/PID',str(pid)])
    print(f"{process_name} 已被成功结束。")

import subprocess

def get_pids_by_process_name_windows(process_name):

    result = subprocess.run(['tasklist', '/FI', f'IMAGENAME eq {process_name}', '/FO', 'CSV'],stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    lines = result.stdout.splitlines()
    pid = ""
    for line in lines:
        parts = line.strip().split(',')
        if len(parts) > 1 and process_name in line:
            pid = parts[1].strip('"')  # 去除引号
    return pid


# # 示例:获取所有名为 '360Safe.exe' 的进程的PID
# pids = get_pids_by_process_name_windows('360Safe.exe')
# print("pids",pids)


if __name__ == '__main__':
    process_name_list = [
        "360tray.exe",
        "safesvr.exe",
        "ZhuDongFangYu.exe",
        "360Safe.exe",
        "360leakfixer.exe",
        "LiveUpdate360.exe",
        "360DesktopLiteApp service",
        "360DesktopService64.exe",
        "ZhuDongFangYu.exe",
        "chrome.exe",
    ]
    for process_name in process_name_list:
        pids = get_pids_by_process_name_windows(process_name)

        print("process_name",process_name)
        print("pids",pids)
        kill_process_by_pid(pids,process_name)

 

posted @ 2024-11-18 10:31  淋哥  阅读(5)  评论(0编辑  收藏  举报