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

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的内容

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