zoukankan      html  css  js  c++  java
  • os.popen(cmd) 与 os.system(cmd) 的区别

    os.popen(cmd) 与 os.system(cmd) 的区别

    1,os.popen(cmd) 不会直接返回任何数据,os.system(cmd) 会直接输出结果(返回的却是int状态码)

    2,os.popen(cmd).read() 才会返回str类型的输出结果,os.system(cmd) 返回的是int状态码

    3,如果需要对输出结果做操作时,需要使用os.popen(cmd).read() 

    tmp = os.popen("ipconfig")
    res = tmp.read()# 要用read()方法读取后才是文本对象
    tmp.close()# 需将对象关闭
    print('==========================')
    print(res)
    print('==========================')
    print(type(res))
    if '192.168.10.' in str(res):
        print('现在是在10网段')
    else:
        print('不在10 网段,请切换网络')
    
    输出:
    ==========================
    Windows IP 配置
    以太网适配器 以太网:
    ............................此处省略...............................
    ............................此处省略...............................
    ==========================
    <class 'str'>
    现在是在10网段
    ip = os.system('ipconfig')
    print('-------------------------')
    print(type(ip))
    print('-------------------------')
    print(str(ip))
    
    输出:
    Windows IP 配置
    以太网适配器 以太网:
    .......................此处省略..........................
    .......................此处省略..........................
    
    -------------------------
    <class 'int'>
    -------------------------
    0

    python通过cmd命令获取本机ip类型及其值

    #encoding:utf-8
     
    import os
    import re
     
    cmd = "ipconfig"
    tmp = os.popen(cmd)
    res = tmp.read()# 要用read()方法读取后才是文本对象
    tmp.close()# 需将对象关闭
    pattern = re.compile('.+:$',re.M)
    ip_type = pattern.findall(res)
    result=[item.strip() for item in res.split("
    ") if item.strip() != "" and (item in ip_type or "IPv4" in item)]
    # for index,item in enumerate(result):
    #     print(index,item)
    index=[len(result)]
    for item in ip_type:
        index.insert(len(index)-1,result.index(item))
    # print(index)
    res=[]
    for i in range(len(index)-1):
        if index[i+1]-index[i]<2:
            index[i]=-1
        else:
            res.append(result[index[i]:index[i+1]])
     
    # index=list(filter(lambda item:item>-1,index))
    # print(index)
    ip_key=[ip[0].split(':')[0].strip() for ip in res]
    ip_value=[ip[1].split(':')[1].strip() for ip in res]
    ip_dic=dict(zip(ip_key,ip_value))
     
    print(ip_dic)


    输出结果:-------------------------------------------------------------

    {
    '以太网适配器 VMware Network Adapter VMnet1': '***.***.***.***',
    '以太网适配器 VMware Network Adapter VMnet8': '***.***.***.***',
    '无线局域网适配器 WLAN': '***.***.***.***'
    }




  • 相关阅读:
    Java操作符,<<、>>等
    abstract的method是否可同时是static,是否可同时是native,是否可同时是synchronized?
    使用JDBC连接各种数据库
    pt-online-schema-change的原理解析与应用说明
    MySQL Online DDL的改进与应用
    细细探究MySQL Group Replicaiton — 配置维护故障处理全集
    关于binary log那些事——认真码了好长一篇
    梳理下MySQL崩溃恢复过程
    说说MySQL中的Redo log Undo log都在干啥
    SQL SERVER大话存储结构(5)_SQL SERVER 事务日志解析
  • 原文地址:https://www.cnblogs.com/111testing/p/13704727.html
Copyright © 2011-2022 走看看