当我们想在程序中结束掉某个已知的任务时
1,获取系统所有pid,pname
2,循环根据name找到指定程序的pid
3,kill(subprocess.Popen("cmd.exe /k taskkill /F /T /PID %i" % pid, shell=True))
举例:杀死我本机的navicat任务
import psutil
def kill_process(name):
pids = psutil.pids()
for pid in pids:
p = psutil.Process(pid)
process_name = p.name()
if name in process_name:
print("Process name is: %s, pid is: %s" % (process_name, pid)) # 1,33664
try:
import subprocess
subprocess.Popen("cmd.exe /k taskkill /F /T /PID %i" % pid, shell=True)
except OSError:
print('没有此进程!!!')
kill_process('navicat')