通过Python在Linux上的进程列表

如何在Linux上使用Python运行进程列表?

国际海事组织看着/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() except IOError: # proc has already terminated continue 

你可以使用psutil作为独立于平台的解决scheme!

 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] 

关于psutil的文档

您可以使用第三方库,如PSI :

PSI是一个Python包,提供对进程和其他各种系统信息(如体系结构,启动时间和文件系统)的实时访问。 它有一个Pythonic API,它在所有支持的平台上都是一致的,但是也可以在需要时公开平台特定的细节。

被批准的创build和使用subprocess的方式是通过subprocess模块。

 import subprocess pl = subprocess.Popen(['ps', '-U', '0'], stdout=subprocess.PIPE).communicate()[0] print pl 

该命令被分解成一个python的参数列表,以便它不需要在shell中运行(默认情况下,subprocess.Popen不使用任何types的shell环境)。 正因为如此,我们无法简单地将“ps -U 0”提供给Popen。

我将使用subprocess模块来执行带有适当选项的命令ps 。 通过添加选项,您可以修改您看到的进程。 很多关于SO的subprocess的例子。 这个问题回答了如何parsingps的输出,例如:)

您可以像示例答案所示,使用PSI模块来访问系统信息(如本例中的过程表)。

我用它来获取所有进程的列表。

 import os processoutput = os.popen("ps -Af").read() print(processoutput) 

弃用:

在Python中列出涉及firefox的进程:

 import os os.system('ps ax | grep firefox | grep -v grep | awk \'{print $1}\') 

在Python中杀死涉及firefox的进程:

 import os os.system('kill $(ps ax | grep firefox | grep -v grep | awk \'{print $1}\')') 

可信的input:

要列出:

 import subprocess print subprocess.check_output('ps ax | grep firefox | grep -v grep | awk \'{print $1}\'',shell=True) 

杀:

 import subprocess print subprocess.check_output('kill $(ps ax | grep firefox | grep -v grep | awk \'{print $1}\')',shell=True)