Splitting out the output of ps using Python

Use the second parameter to split which specifies the maximum number of fields to split the string into. I guess you can find the number by counting the number of fields in the first line, i.e. the column titles.

ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
processes = ps.split('\n')
# this specifies the number of splits, so the splitted lines
# will have (nfields+1) elements
nfields = len(processes[0].split()) - 1
for row in processes[1:]:
    print row.split(None, nfields)

Leave a Comment