zoukankan      html  css  js  c++  java
  • 【subprocess】专项

    1. 快速查询手册
    
    from subprocess import DEVNULL
    import subprocess
    
    # 会挂住等待执行完成,返回交互内容
    # p1 = subprocess.Popen(['ping', '1.1.1.1'], stdout=subprocess.PIPE).communicate()[0]
    # stdout, stderr = child.communicate()
    # print(p1.decode('gbk'))
    
    
    # 会挂住等待执行完成,返回执行状态 0成功,1失败
    # ping = subprocess.call('ping 1.1.1.1',stdout=DEVNULL, stderr=subprocess.STDOUT,shell=False)
    # print(ping)
    
    
    # 会挂住等待执行完成,返回执行状态 0成功,1失败
    # 和call等效
    # ping = subprocess.Popen('ping 1.1.1.1',stdout=DEVNULL, stderr=subprocess.STDOUT,shell=False).wait()
    # ping = subprocess.Popen('ping 1.1.1.1',stdout=subprocess.PIPE, stderr=subprocess.STDOUT,shell=False).wait() # 和上面一样
    # print(ping)
    
    
    # 不会挂住,返回subprocess.Popen对象【主程序退出后,子进程还在运行】
    # ping = subprocess.Popen('ping 1.1.1.1',stdout=DEVNULL, stderr=subprocess.STDOUT,shell=False)
    # print(ping)
    
    
    # 会挂住等待执行完成,返回交互内容
    ping = subprocess.Popen('ping 127.0.0.1',stdout=subprocess.PIPE, stderr=subprocess.STDOUT,shell=False)
    # rst = ping.stdout.readlines() # 返回列表
    # rst = ping.stdout.read()     # 返回字符串
    rst = ping.stdout.read().decode('gbk')
    print(rst)
    
    
    
    # 会挂住等待执行完成,【实时】返回交互内容
    ping = subprocess.Popen('ping 127.0.0.1',stdout=subprocess.PIPE, stderr=subprocess.STDOUT,shell=False)
    for i in iter(ping.stdout.readline,b''):
        print(i.strip().decode('gbk'))
    
    
    
    
    # 如果子进程还需要输入,则可以通过communicate()方法输入:
    p = subprocess.Popen(['nslookup'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, err = p.communicate(b'set q=mx
    python.org
    exit
    ')
    print(output.decode('utf-8'))
    print('Exit code:', p.returncode)
    上面的代码相当于在命令行执行命令nslookup,然后手动输入:
    set q=mx
    python.org
    exit
    
    
  • 相关阅读:
    HDU 3389 Game (阶梯博弈)
    国内操作系统OS分析(上)
    激光雷达应用技术分析
    构建深度学习框架运行平台
    GitHub上YOLOv5开源代码的训练数据定义
    GitHub上开源的YOLOv5
    深度学习调用TensorFlow、PyTorch等框架
    CUDA C 纹理提取Texture Fetching
    CPU,GPU,GPGPU
    毫米波RADAR与LIDAR探秘
  • 原文地址:https://www.cnblogs.com/amize/p/15188215.html
Copyright © 2011-2022 走看看