Python获取命令行结果

转载链接:https://blog.csdn.net/wowocpp/article/details/80775650

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))  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

运行结果:

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

E:\Program\Python>  
  • 1
  • 2
  • 3
  • 4

python执行系统命令后获取返回值的几种方式

第一种情况

os.system('ps aux')  
  • 1

执行系统命令,没有返回值 
第二种情况

result = os.popen('ps aux')  
      res = result.read()  
      for line in res.splitlines():  
              print line  
  • 1
  • 2
  • 3
  • 4

执行系统命令,可以获取执行系统命令的结果

p = subprocess.Popen('ps aux',shell=True,stdout=subprocess.PIPE)  
   out,err = p.communicate()  
   for line in out.splitlines():  
       print line  
  • 1
  • 2
  • 3
  • 4

同上,执行系统命令,可以获取执行系统命令的结果 
第三种情况

output = commands.getstatusoutput('ps aux')  
print  output  
  • 1
  • 2

执行系统命令,并获取当前函数的返回值

猜你喜欢

转载自blog.csdn.net/Jum_Summer/article/details/81434307