本文實(shí)例講述了Python實(shí)現(xiàn)獲取命令行輸出結(jié)果的方法。分享給大家供大家參考,具體如下:
Python獲取命令行輸出結(jié)果,并對(duì)結(jié)果進(jìn)行過濾找到自己需要的!
這里以獲取本機(jī)MAC地址和IP地址為例!
# coding: GB2312import os, re# execute command, and return the outputdef execCmd(cmd):  r = os.popen(cmd)  text = r.read()  r.close()  return text# write "data" to file-filenamedef writeFile(filename, data):  f = open(filename, "w")  f.write(data)  f.close()# 獲取計(jì)算機(jī)MAC地址和IP地址if __name__ == '__main__':  cmd = "ipconfig /all"  result = execCmd(cmd)  pat1 = "Physical Address[/. ]+: ([/w-]+)"  pat2 = "IP Address[/. ]+: ([/./d]+)"  MAC = re.findall(pat1, result)[0]    # 找到MAC  IP = re.findall(pat2, result)[0]    # 找到IP  print("MAC=%s, IP=%s" %(MAC, IP))運(yùn)行結(jié)果:
E:/Program/Python>del.pyMAC=00-1B-77-CD-62-2B, IP=192.168.1.110E:/Program/Python>
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python字符串操作技巧匯總》、《Python常用遍歷技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選