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': '***.***.***.***'
}