python3 进程中 获取进程号和杀死进程
转载:https://blog.csdn.net/Teddycxr/article/details/80804383
遍历搜寻及测试总结三种方法:
1. signal
import os,signal out=os.popen("ps aux | grep xx.py").read() for line in out.splitlines(): print(line) if 'BcexServices.py' in line: pid = int(line.split()[1]) print(pid) os.kill(pid,signal.SIGKILL) def kill(pid): try: a = os.kill(pid, signal.SIGKILL) print('已杀死pid为%s的进程, 返回值是:%s' % (pid, a)) except OSError: print('没有如此进程!!!')
2. psutil
import psutil def processinfo(processName): pids = psutil.pids() for pid in pids: # print(pid) p = psutil.Process(pid) # print(p.name) if p.name() == processName: print(pid) return True # 如果找到该进程则打印它的PID,返回true return False # 没有找到该进程,返回false processinfo('你的文件名.py')
3. psutil 的另外一种方式
for proc in psutil.process_iter(): print("pid-%d,name:%s" % (proc.pid,proc.name()))