範例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]
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