1

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?

1
  • Instead of doing it in python, you could also take advantage of the sort command in the shell: ps aux | sort --key=10. Of course, this would not strip off the first row. For that, you'd need something like awk: ps aux | awk 'NR != 1 {print;}' | sort --key=10 Commented Jan 8, 2013 at 7:14

2 Answers 2

2

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:])
Sign up to request clarification or add additional context in comments.

Comments

2
sorted(..., key=lambda x: x.split()[10])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.