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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1091327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:27:56  来源:igfitidea点击:

how do I get the process list in Python?

pythonunixkillpsprocesslist

提问by Johan Carlsson

How do I get a process list of all running processes from Python, on Unix, containing then name of the command/process and process id, so I can filter and kill processes.

如何在 Unix 上从 Python 获取所有正在运行的进程的进程列表,其中包含命令/进程的名称和进程 ID,以便我可以过滤和终止进程。

采纳答案by krawyoti

On linux, the easiest solution is probably to use the external pscommand:

在 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')]]

On other systems you might have to change the options to ps.

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

Still, you might want to run manon pgrepand pkill.

不过,你可能想运行manpgreppkill

回答by Giampaolo Rodolà

The right portable solution in Python is using psutil. You have different APIs to interact with PIDs:

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()

...and if you want to "search and kill":

...如果你想“搜索并杀死”:

for p in psutil.process_iter():
    if 'nginx' in p.name() or 'nginx' in ' '.join(p.cmdline()):
        p.terminate()
        p.wait()

回答by Vinay Sajip

On Linux, with a suitably recent Python which includes the subprocessmodule:

在 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

You may need to tweak the ps command slightly depending on your exact needs.

您可能需要根据您的确切需要稍微调整 ps 命令。

回答by nik

Why Python?
You can directly use killallon the process name.

为什么是 Python?
您可以直接killall在进程名称上使用。