轉載: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()))
