如何在Python中获取进程列表?
我想知道怎么用Python在Unix系统上获取所有正在运行的进程列表,这个列表需要包含每个进程的名称和进程ID,这样我就可以筛选和结束某些进程。
5 个回答
12
在Linux系统上,如果你使用的是比较新的Python版本,并且这个版本包含了subprocess
模块:
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命令。
32
在Python中,最合适的便携式解决方案是使用 psutil 这个库。它提供了不同的接口,让你可以和进程ID(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()
2
在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
命令来查看。