python --subprocess 范例

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

import subprocess
handle = open(r'd:\tmp.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的内容ide

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

 

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

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通讯一次以后即关闭了管道.这时能够试试下面的方法:code

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