如何在 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
how do I get the process list in Python?
提问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 ps
command:
在 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 man
on pgrep
and pkill
.
不过,你可能想运行man
的pgrep
和pkill
。
回答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 subprocess
module:
在 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 命令。