如何从Unix获得所有正在运行的进程列表,包括命令/进程名称和进程标识,这样我就可以过滤和终止进程。
在Linux上,最简单的解决方案可能是使用外部ps
命令:
>>> import os >>> data = [(int(p), c) for p, c in [x.rstrip('\n').split(' ', 1) \ ... for x in os.popen('ps h -eo pid:1,command')]]
在其他系统上,您可能必须将选项更改为ps
。
不过,你可能想在pgrep
和pkill
上运行man
。
在Linux上,使用包含subprocess
模块的最新Python:
from subprocess import Popen, PIPE process = Popen(['ps', '-eo' ,'pid,args'], stdout=PIPE, stderr=PIPE) stdout, notused = process.communicate() for line in stdout.splitlines(): pid, cmdline = line.split(' ', 1) #Do whatever filtering and processing is needed
您可能需要根据您的确切需要稍微调整ps命令。
Python中正确的便携式解决方案是使用psutil 。 您有不同的API与PID进行交互:
>>> import psutil >>> psutil.pids() [1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, ..., 32498] >>> psutil.pid_exists(32498) True >>> p = psutil.Process(32498) >>> p.name() 'python' >>> p.cmdline() ['python', 'script.py'] >>> p.terminate() >>> p.wait()
…如果你想“搜索和杀死”:
for p in psutil.process_iter(): if 'nginx' in p.name() or 'nginx' in ' '.join(p.cmdline()): p.terminate() p.wait()
为什么是Python?
您可以直接在进程名称上使用killall
。