通过 Python 在 Linux 上的进程列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2703640/
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
Process list on Linux via Python
提问by Madzombie
How can I get running process list using Python on Linux?
如何在 Linux 上使用 Python 获取正在运行的进程列表?
回答by extraneon
I would use the subprocessmodule to execute the command ps
with appropriate options. By adding options you can modify which processes you see. Lot's of examples on subprocess on SO. This questionanswers how to parse the output of ps
for example:)
我将使用子过程模块以ps
适当的选项执行命令。通过添加选项,您可以修改您看到的进程。很多关于 SO 子流程的例子。这个问题回答了如何解析ps
例如的输出:)
You can, as one of the example answers showedalso use the PSImodule to access system information (such as the process table in this example).
回答by ars
You can use a third party library, such as PSI:
您可以使用第三方库,例如PSI:
PSI is a Python package providing real-time access to processes and other miscellaneous system information such as architecture, boottime and filesystems. It has a pythonic API which is consistent accross all supported platforms but also exposes platform-specific details where desirable.
PSI 是一个 Python 包,提供对进程和其他杂项系统信息(如体系结构、启动时间和文件系统)的实时访问。它有一个 pythonic API,它在所有支持的平台上都是一致的,但也在需要的地方公开特定于平台的细节。
回答by bobince
IMO looking at the /proc
filesystem is less nasty than hacking the text output of ps
.
IMO 查看/proc
文件系统比破解ps
.
import os
pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]
for pid in pids:
try:
print open(os.path.join('/proc', pid, 'cmdline'), 'rb').read().split('import subprocess
pl = subprocess.Popen(['ps', '-U', '0'], stdout=subprocess.PIPE).communicate()[0]
print pl
')
except IOError: # proc has already terminated
continue
回答by Matt
The sanctioned way of creating and using child processes is through the subprocess module.
创建和使用子进程的认可方式是通过 subprocess 模块。
import psutil
psutil.pids()
[1, 2, 3, 4, 5, 6, 7, 46, 48, 50, 51, 178, 182, 222, 223, 224,
268, 1215, 1216, 1220, 1221, 1243, 1244, 1301, 1601, 2237, 2355,
2637, 2774, 3932, 4176, 4177, 4185, 4187, 4189, 4225, 4243, 4245,
4263, 4282, 4306, 4311, 4312, 4313, 4314, 4337, 4339, 4357, 4358,
4363, 4383, 4395, 4408, 4433, 4443, 4445, 4446, 5167, 5234, 5235,
5252, 5318, 5424, 5644, 6987, 7054, 7055, 7071]
The command is broken down into a python list of arguments so that it does not need to be run in a shell (By default the subprocess.Popen does not use any kind of a shell environment it just execs it). Because of this we cant simply supply 'ps -U 0' to Popen.
该命令被分解为一个 Python 参数列表,因此它不需要在 shell 中运行(默认情况下 subprocess.Popen 不使用任何类型的 shell 环境,它只是执行它)。因此,我们不能简单地向 Popen 提供“ps -U 0”。