您的位置:首页 > 编程语言 > Python开发

python获取命令行输出结果

2012-03-17 11:59 549 查看
python获取命令行输出结果,并对结果进行过滤找到自己需要的!

这里以获取本机MAC地址和IP地址为例!

# coding: GB2312
import os, re

# execute command, and return the output
def execCmd(cmd):
r = os.popen(cmd)
text = r.read()
r.close()
return text

# write "data" to file-filename
def writeFile(filename, data):
f = open(filename, "w")
f.write(data)
f.close()

# 获取计算机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))


运行结果:

E:\Program\Python>del.py
MAC=00-1B-77-CD-62-2B, IP=192.168.1.110

E:\Program\Python>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python cmd command import os