Python实现获取命令行输出结果的方法

yipeiwu_com6年前Python基础

本文实例讲述了Python实现获取命令行输出结果的方法。分享给大家供大家参考,具体如下:

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相关内容可查看本站专题:《Python字符串操作技巧汇总》、《Python常用遍历技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

python3.4实现邮件发送功能

本文实例为大家分享了python实现邮件发送功能的具体代码,供大家参考,具体内容如下 import smtplib import os from email.mime.text...

Django 拆分model和view的实现方法

Django 拆分model和view的实现方法

在标准的dgango项目中,自动生成的目录结构会包括models.py和views.py两个文件,分别在里面写model的代码和controller的代码,但是所有的代码都写在一个文件里...

python中的错误处理

用错误码来表示是否出错十分不便,因为函数本身应该返回的正常结果和错误码混在一起,造成调用者必须用大量的代码来判断是否出错: def foo(): r = some_functio...

Python函数嵌套实例

在Python中函数可以作为参数进行传递,而也可以赋值给其他变量(类似Javascript,或者C/C++中的函数指针); 类似Javascript,Python支持函数嵌套,Javas...

python xml解析实例详解

python xml解析 first.xml  <info> <person > <id>1</id> <n...