如何在Python中获取进程列表?

Joh*_*son 7 python unix kill ps processlist

如何从Unix获取所有正在运行的进程的进程列表,包含命令/进程名称和进程ID,因此我可以过滤和终止进程.

Vin*_*jip 7

在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
Run Code Online (Sandbox Code Playgroud)

您可能需要根据具体需要稍微调整ps命令.

  • @Itération122442 这意味着最近足以包含“subprocess”模块 - 所以 2.4-2.7、3.5+。 (2认同)

Gia*_*olà 5

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()
Run Code Online (Sandbox Code Playgroud)

......如果你想"搜索并杀死":

for p in psutil.process_iter():
    if 'nginx' in p.name() or 'nginx' in ' '.join(p.cmdline()):
        p.terminate()
        p.wait()
Run Code Online (Sandbox Code Playgroud)


kra*_*oti 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')]]
Run Code Online (Sandbox Code Playgroud)

在其他系统上,您可能必须将选项更改为ps.

不过,您可能想manpgrep和 上运行pkill

  • os.popen 已弃用。使用子流程模块。 (2认同)