1

我有一个数组,其中包含“ps aux”命令的输出。我的目标是使用命令名称列对数组进行排序,但我不知道该怎么做,也找不到答案。

到目前为止,这是我的代码

#!/usr/bin/python
import subprocess

ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
processes = ps.split('\n')

nfields = len(processes[0].split()) - 1
for row in processes[1:]:
#    print row.split(None, nfields) //This is used to split all the value in the string
     print row

此代码片段的输出类似于

...
root        11  0.0  0.0      0     0 ?        S<    2012   0:00 [kworker/1:0H]
root        12  0.0  0.0      0     0 ?        S     2012   0:00 [ksoftirqd/1]
root        13  0.0  0.0      0     0 ?        S     2012   0:00 [migration/2]

...

所以我的目标会有类似的输出,但在最后一列排序,所以最后它看起来像这样

...
root        13  0.0  0.0      0     0 ?        S     2012   0:00 [migration/2]
root        12  0.0  0.0      0     0 ?        S     2012   0:00 [ksoftirqd/1]
root        11  0.0  0.0      0     0 ?        S<    2012   0:00 [kworker/1:0H]
...

你们中的任何人都知道如何做到这一点?

4

2 回答 2

2

像这样的东西:

#!/usr/bin/env python
import subprocess
from operator import itemgetter

ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
processes = [p for p in ps.split('\n') if p]
split_processes = [p.split() for p in processes]

然后像这样打印出你的结果:

for row in sorted(split_processes[1:], key=itemgetter(10)):
    print " ".join(row)

或像这样(如果您只想要进程名称和参数):

for row in sorted(split_processes[1:], key=itemgetter(10)):
    print " ".join(row[10:])
于 2013-01-08T06:31:59.383 回答
2
sorted(..., key=lambda x: x.split()[10])
于 2013-01-08T06:03:12.047 回答