os.popen(cmd) 与 os.system(cmd) 的区别
1,os.popen(cmd) 不会直接返回任何数据,os.system(cmd) 会直接输出结果(返回的却是int状态码)
2,os.popen(cmd).read() 才会返回str类型的输出结果,os.system(cmd) 返回的是int状态码
3,如果需要对输出结果做操作时,需要使用os.popen(cmd).read()
tmp = os.popen("ipconfig") res = tmp.read()# 要用read()方法读取后才是文本对象 tmp.close()# 需将对象关闭 print('==========================') print(res) print('==========================') print(type(res)) if '192.168.10.' in str(res): print('现在是在10网段') else: print('不在10 网段,请切换网络') 输出: ========================== Windows IP 配置 以太网适配器 以太网: ............................此处省略............................... ............................此处省略............................... ========================== <class 'str'> 现在是在10网段
ip = os.system('ipconfig') print('-------------------------') print(type(ip)) print('-------------------------') print(str(ip)) 输出: Windows IP 配置 以太网适配器 以太网: .......................此处省略.......................... .......................此处省略.......................... ------------------------- <class 'int'> ------------------------- 0
python通过cmd命令获取本机ip类型及其值
#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)
输出结果:-------------------------------------------------------------
{
'以太网适配器 VMware Network Adapter VMnet1': '***.***.***.***',
'以太网适配器 VMware Network Adapter VMnet8': '***.***.***.***',
'无线局域网适配器 WLAN': '***.***.***.***'
}