python 调用系统 cmd命令获取本机 ip地址,得到结果:
{
'以太网适配器 VMware Network Adapter VMnet1': '***.***.***.***',
'以太网适配器 VMware Network Adapter VMnet8': '***.***.***.***',
'无线局域网适配器 WLAN': '***.***.***.***'
}
实现代码如下:
#encoding:utf-8
import os
import re
cmd = "ipconfig"
tmp = os.popen(cmd)
res = tmp.read()# 要用read()方法读取后才是文本对象
tmp.close()# 需将对象关闭
pattern = re.compile('.+:$',re.M)
ip_type = pattern.findall(res)
result=[item.strip() for item in res.split("\n") if item.strip() != "" and (item in ip_type or "IPv4" in item)]
# for index,item in enumerate(result):
# print(index,item)
index=[len(result)]
for item in ip_type:
index.insert(len(index)-1,result.index(item))
# print(index)
res=[]
for i in range(len(index)-1):
if index[i+1]-index[i]<2:
index[i]=-1
else:
res.append(result[index[i]:index[i+1]])
# index=list(filter(lambda item:item>-1,index))
# print(index)
ip_key=[ip[0].split(':')[0].strip() for ip in res]
ip_value=[ip[1].split(':')[1].strip() for ip in res]
ip_dic=dict(zip(ip_key,ip_value))
print(ip_dic)