zoukankan      html  css  js  c++  java
  • python --subprocess 范例

    范例1:查看ipconfig -all命令的输出,并将将输出保存到文件tmp.log中:

    import subprocess
    handle = open(r'd:	mp.log','w')
    p=subprocess.Popen(['ipconfig','-all'], stdout=handle)
    if p.poll()==None:
      print "end<<<<<<<<<<<<<<<<"
      p.terminate()
      handle.close()

    范例2:查看网络设置ipconfig -all,保存到变量中:

    #coding:utf-8
    import subprocess
    output = subprocess.Popen(['ipconfig','-all'], stdout=subprocess.PIPE,shell=True)
    oc=output.communicate()#取出output中的字符串
    print oc[0]#打印网络信息

    范例3:显示文件t2.py的内容

    import subprocess
    y=subprocess.check_output(["type", "t2.py"],shell=True)
    print(y)

    范例4: 调用系统中cmd命令,显示命令执行的结果

    import subprocess
    x=subprocess.check_output(["echo", "Hello World!"],shell=True)
    print(x)

    范例5:在Popen()建立子进程的时候改变标准输入、标准输出和标准错误,并可以利用subprocess.PIPE将多个子进程的输入和输出连接在一起,构成管道(pipe):

    import subprocess
    child1 = subprocess.Popen(["dir", "/w"], stdout=subprocess.PIPE,shell=True)
    child2 = subprocess.Popen(["echo", "hello"], stdin=child1.stdout,stdout=subprocess.PIPE,shell=True)
    out1 = child1.communicate()
    out2 = child2.communicate()
    print out2[0]
    print "********************"
    for i in range(len(out1)):
        print out1[i]
        

    范例6:如果想频繁地和子线程通信,那么不能使用communicate();因为communicate通信一次之后即关闭了管道.这时可以试试下面的方法:

    import subprocess
    p=subprocess.Popen("dir", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)  
    while True:  
        buff = p.stdout.readline()  
        if buff == '' and p.poll() != None:  
            break 
  • 相关阅读:
    SpringBoot自定义过滤器的两种方式及过滤器执行顺序
    如何用上新版本的 IDEA(IDEA 2019.2.2版本)
    IDEA乱码Tomcat控制台乱码输出乱码报文乱码
    单例模式的几种实现方式及对比
    Java中synchronized关键字你知道多少
    [转载]Vertica “ERROR: Too many ROS containers exist”
    FTP Client
    统计数据库表大小
    常用JS代码整理
    WinForm 控件不闪烁
  • 原文地址:https://www.cnblogs.com/saryli/p/5086755.html
Copyright © 2011-2022 走看看