Python获取应用进程PID杀死Linux进程
代码如下(示例):
import os
import subprocess
import time
def get_process_id(name):
child = subprocess.Popen(["pgrep", "-f", name], stdout=subprocess.PIPE, shell=False)
response = child.communicate()[0]
return [int(pid) for pid in response.split()]
def kill_all():
tsdict = {'name': {'name1', 'name2', 'name3', 'name4'}}
for i in tsdict['name']:
pids = get_process_id(i)
if not pids:
print("未找到%s进程" % i)
# sys.exit(1)
else:
for pid in pids:
print('找到%s进程,进程pid为:' % i, pid)
result = os.system("kill -9 " + str(pid))
if result == 0:
print(f'%s进程成功被杀死 !\n进程pid为: {pid} \n' % i)
time.sleep(1)
time.sleep(1)
if __name__ == '__main__':
kill_all()
time.sleep(1)