ANV
ANV

Reputation: 51

How do I extract a column from text using Python?

I am a newbie in python programing. Wrote this script by searching in python docs from internet.

Could anybody please help me to get only the second column as output of "ps aux" command(ie only the PID Column).

#script to print the processid
import os
import commands
out=commands.getoutput('ps aux') # to get the process listing in out
#print out
#print out[2] #print only second column from out
print out[:2] 

output of "print out" statement
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0   5728  1068 ?        Ss   Oct13   0:07 /sbin/init
root         2  0.0  0.0      0     0 ?        S<   Oct13   0:00 [kthreadd]
root         3  0.0  0.0      0     0 ?        S<   Oct13   0:00 [migration/0]
root         4  0.0  0.0      0     0 ?        S<   Oct13   0:11 [ksoftirqd/0]
root         5  0.0  0.0      0     0 ?        S<   Oct13   0:00 [watchdog/0]
root         6  0.0  0.0      0     0 ?        S<   Oct13   0:00 [migration/1]

Thanks in advance

Upvotes: 5

Views: 9617

Answers (2)

Russell Dias
Russell Dias

Reputation: 73402

As mentioned in the comments this is very straightforward to do using awk:

ps aux | awk {'print $2'}

However, here is also a python solution using a list comprehension, which gives you a list of PID's:

>>> [col.split()[1] for col in out.splitlines()]
['PID', '1', '2', '3', '4', '5', '6']

Upvotes: 3

Raymond Hettinger
Raymond Hettinger

Reputation: 226754

Use split() and splitlines() (to convert the string into a list of lines, and the list of lines into a list of columns that you can then index as needed):

>>> for line in out.splitlines():
...     fields = line.split()
...     if len(fields) >= 2:
...         print fields[1]


PID
1
2
3
4
5
6

Upvotes: 3

Related Questions