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': '***.***.***.***'
    }




  • 相关阅读:
    MFC 记录 CreateProcess启动外部游戏主程序
    MFC 记录 CListCtrl 学习使用
    MS SQL自定义字符串拆分函数的惨痛经历
    C#路径/文件/目录/I/O常见操作汇总
    2012年开发者该做的11件事
    取出AD中一個組的所有成員信息(C#實現功能配合EXT做的界面)
    代码注释规范
    基于工作实际需求的Ext.Net和C#搭配应用之一 取出网域(AD)中所有计算机名及位置描述等信息
    2012,我的C#全能Excel操作(无需Office,不使用XML)
    一個文件文件和路徑的類
  • 原文地址:https://www.cnblogs.com/111testing/p/13704727.html
Copyright © 2011-2022 走看看