python根据进程名称获取进程id、taskkill进程
import os
import psutil
from psutil import NoSuchProcess
class ProcessUtilCls:
# 停止进程(windows)。
# 参数:tag =1时按照process_name停止进程,否则按照pids[pid1,pid2...]停止进程
@staticmethod
def process_do_taskkill(tag: int, pids: list, p_name='chrome.exe'):
if 1 == tag:
_cmd = 'taskkill /im ' + p_name + ' /F > NULL'
p_name = p_name.lower()
for _p in psutil.process_iter():
if p_name in _p.name():
os.system(_cmd)
else:
for i in pids:
_cmd = 'taskkill /PID ' + str(i) + ' /F > NULL'
os.system(_cmd)
# 根据process_name得到相关的所有pid
@staticmethod
def get_pids(pname: str):
# 当前所有pid
current_pids = [p.pid for p in psutil.process_iter()]
_l = []
for i in current_pids:
try:
_p = psutil.Process(i)
except NoSuchProcess:
continue
if pname == _p.name():
# 保存process_name=pname的所有pid
_l.append(i)
return _l
# 比对两个list,返回after相较于before的差集
@staticmethod
def diff_2list(before: list, after: list):
_l = []
t = {}
for i in before:
t[i] = 1
for i in after:
if t.get(i) is None:
_l.append(i)
return _l
ProcessUtil = ProcessUtilCls()
标签:name,psutil,python,pid,process,windows,pids,taskkill From: https://www.cnblogs.com/jinziguang/p/18323974