Python将行转换为列表

Python将行转换为列表,python,Python,我使用ifconfig命令和awk捕获系统的ip地址 $ ifconfig | grep -E 'inet.[0-9]' | awk '{ print $2}' 127.0.0.1 192.168.8.2 如何使用python将o/p转换为列表?使用sys.stdin读取此输出 import sys list_of_lines = [line.strip() for line in sys.stdin] 然后重定向输出,如下所示: $ ifconfig | grep -E 'inet.

我使用ifconfig命令和awk捕获系统的ip地址

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

127.0.0.1
192.168.8.2

如何使用python将o/p转换为列表?

使用
sys.stdin
读取此输出

import sys
list_of_lines = [line.strip() for line in sys.stdin]
然后重定向输出,如下所示:

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

谢谢大家。我可以这样做

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

您可以直接跳过外壳处理来调用命令管道。您可以在不离开Python的情况下获得IP地址。如果您只需要非环回IP:

>>> socket.gethostbyname_ex(socket.gethostname())
('furby.home', [], ['192.168.1.5'])
>>> socket.gethostbyname_ex(socket.gethostname())[2][0]
'192.168.1.5'
为了得到回环

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

还有一个名为的模块,将在中执行此操作

我刚刚修改了@Pujan发布的代码,使之适用于linux。(在Ubuntu 12.04中测试):


我不确定我们是否可以通过这个知道IPv6地址?这是一个好问题,目前我还没有答案。我会检查一下,看看能做些什么。
>>> socket.gethostbyname_ex('localhost')
('localhost', [], ['127.0.0.1'])
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