前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python获取命令行输出结果

python获取命令行输出结果

作者头像
py3study
发布2020-01-10 20:28:02
4.3K0
发布2020-01-10 20:28:02
举报
文章被收录于专栏:python3python3python3

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执行系统命令后获取返回值的几种方式

第一种情况

os.system('ps aux')  

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

result = os.popen('ps aux')  
      res = result.read()  
      for line in res.splitlines():  
              print line  

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

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

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

output = commands.getstatusoutput('ps aux')  
print  output  

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-08-26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • python执行系统命令后获取返回值的几种方式
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档