我有一个数组,其中包含“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]
...
你们中有人知道如何执行此操作吗?
最佳答案
像这样:
#!/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:])
关于Python用子串排序字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14209064/