Python结束外部程序

大同小异,都是结束进程

import os
import subprocess
import time

import psutil
import win32api
import signal
import win32process


def kill1(myName):
    subprocess.call('taskkill /F /IM ' + myName)


def kill2(myName):
    os.system(r'taskkill /F /IM '+myName)


def kill3(myName):
    pids = psutil.pids()
    for pid in pids:
        p = psutil.Process(pid)
        if p.name() == myName:
            try:
                kill_pid = os.kill(pid, signal.SIGABRT)
                print('已杀死pid为%s的进程, 返回值是:%s' % (pid, kill_pid))
                return
            except Exception as e:
                print('没有如此进程!!!', e)


def kill4(myName):
    pids = psutil.pids()
    for pid in pids:
        
        p = psutil.Process(pid)
        if p.name() == myName:
            try:
                kill_pid = os.popen('taskkill.exe /F /pid:' + str(pid))
                print('已杀死pid为%s的进程, 返回值是:%s' % (pid, kill_pid))
                return
            except Exception as e:
                print('没有如此进程!!!', e)


def kill5(myName):
    pids = psutil.pids()
    for pid in pids:
        p = psutil.Process(pid)
        if p.name() == myName:
            try:
                handle = win32api.OpenProcess(1, False, pid)  # 打开一个已存在的进程对象,并返回进程的句柄
                win32process.TerminateProcess(handle, -1)
                win32api.CloseHandle(handle)  # 关闭当前打开的文件句柄
                print('已杀死pid为%s的进程' % pid)
                return
            except Exception as e:
                print('没有如此进程!!!', e)


if __name__ == "__main__":
    print(111)
    name = "ZJ_mtt.exe"
    # 1
    win32api.ShellExecute(0, 'open', 'C:\\Users\\zlh\\Desktop\\1\\' + name, '', '', 1)
    time.sleep(1)
    kill1(name)
    time.sleep(1)
    # 2
    win32api.ShellExecute(0, 'open', 'C:\\Users\\zlh\\Desktop\\1\\' + name, '', '', 1)
    time.sleep(1)
    kill2(name)
    time.sleep(1)
    # 3
    win32api.ShellExecute(0, 'open', 'C:\\Users\\zlh\\Desktop\\1\\' + name, '', '', 1)
    time.sleep(1)
    kill3(name)
    time.sleep(1)
    # 4
    win32api.ShellExecute(0, 'open', 'C:\\Users\\zlh\\Desktop\\1\\' + name, '', '', 1)
    time.sleep(1)
    kill4(name)
    time.sleep(1)
    # 5
    win32api.ShellExecute(0, 'open', 'C:\\Users\\zlh\\Desktop\\1\\' + name, '', '', 1)
    time.sleep(1)
    kill5(name)
最后修改:2021 年 11 月 16 日
如果觉得我的文章对你有用,请随意赞赏