Pujan
Pujan

Reputation: 3254

Python Convert Lines into a list

I use ifconfig command with awk to catch system's ip addresses

$ ifconfig  | grep -E 'inet.[0-9]' | awk '{ print $2}'

127.0.0.1
192.168.8.2

How to convert o/p into a list using python ?

Upvotes: 0

Views: 7930

Answers (6)

bdur
bdur

Reputation: 339

I just modified the code posted by @Pujan to make it work for linux. (tested in Ubuntu 12.04):

import os
ipa=[]
f=os.popen("/sbin/ifconfig | grep -i \"inet\" | grep -iv \"inet6\" | " +   "awk {'print $2'} | sed -ne 's/addr\:/ /p'")
for i in f.readlines():
    ipa.append(i.rstrip('\n'))
print ipa

Upvotes: 1

jonesy
jonesy

Reputation: 3542

You might just skip shelling out to call a pipeline of commands. You can get the IP addresses without leaving Python. If you just need the non-loopback IP:

>>> socket.gethostbyname_ex(socket.gethostname())
('furby.home', [], ['192.168.1.5'])
>>> socket.gethostbyname_ex(socket.gethostname())[2][0]
'192.168.1.5'

And to get the loopback,

>>> socket.gethostbyname_ex('localhost')
('localhost', [], ['127.0.0.1'])

There's also a module called netifaces that'll do this in one fell swoop.

Upvotes: 3

Pujan
Pujan

Reputation: 3254

Thanks all . I could do this way.

ipa=[]
f=os.popen("ifconfig  | grep -E 'inet.[0-9]' | awk '{ print $2}'")
for i in f.readlines():
     ipa.append(i.rstrip('\n'))
return ipa

Upvotes: 1

Richard Nienaber
Richard Nienaber

Reputation: 10564

import subprocess
lines = subprocess.check_output(["ifconfig  | grep -E 'inet.[0-9]' | awk '{ print $2
}'"]).split('\n')

Upvotes: 1

inspectorG4dget
inspectorG4dget

Reputation: 113915

Use sys.stdin to read this output.

Then redirect the output as follows:

$ ifconfig  | grep -E 'inet.[0-9]' | awk '{ print $2}' | myProg.py

Upvotes: 0

Amber
Amber

Reputation: 526573

import sys
list_of_lines = [line.strip() for line in sys.stdin]

Upvotes: 6

Related Questions