Reputation: 912
I have an array which contains the ouput of the "ps aux" command. My goal is to sort the array with the command name column but I have no idea how to do this and I can't manage to find an answer.
Here's my code so far
#!/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
The output of this code snipet is something like
...
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]
...
So my goal would have a similar output but sorted on the last column so in the end it would looks like this
...
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]
...
Anyone of you have any clues on how to do this?
Upvotes: 1
Views: 215
Reputation: 49013
Something like this:
#!/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]
And then print out your results like this:
for row in sorted(split_processes[1:], key=itemgetter(10)):
print " ".join(row)
or like this (if you want only the process name and arguments):
for row in sorted(split_processes[1:], key=itemgetter(10)):
print " ".join(row[10:])
Upvotes: 2