本文實例講述了Python中subprocess模塊用法。分享給大家供大家參考。具體如下:
執行命令:
>>> subprocess.call(["ls", "-l"])0>>> subprocess.call("exit 1", shell=True)1測試調用系統中cmd命令,顯示命令執行的結果:
x=subprocess.check_output(["echo", "Hello World!"],shell=True)print(x)"Hello World!"
測試在python中顯示文件內容:
y=subprocess.check_output(["type", "app2.cpp"],shell=True)print(y) #include <iostream> using namespace std; ......
查看ipconfig -all命令的輸出,并將將輸出保存到文件tmp.log中:
handle = open(r'd:/tmp.log','wt')subprocess.Popen(['ipconfig','-all'], stdout=handle)
查看網絡設置ipconfig -all,保存到變量中:
output = subprocess.Popen(['ipconfig','-all'], stdout=subprocess.PIPE,shell=True)oc=output.communicate()#取出output中的字符串#communicate() returns a tuple (stdoutdata, stderrdata).print(oc[0]) #打印網絡信息Windows IP Configuration Host Name . . . . .
我們可以在Popen()建立子進程的時候改變標準輸入、標準輸出和標準錯誤,并可以利用subprocess.PIPE將多個子進程的輸入和輸出連接在一起,構成管道(pipe):
child1 = subprocess.Popen(["dir","/w"], stdout=subprocess.PIPE,shell=True)child2 = subprocess.Popen(["wc"], stdin=child1.stdout,stdout=subprocess.PIPE,shell=True)out = child2.communicate()print(out) (' 9 24 298/n', None)如果想頻繁地和子線程通信,那么不能使用communicate();因為communicate通信一次之后即關閉了管道.這時可以試試下面的方法:
p= subprocess.Popen(["wc"], stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)p.stdin.write('your command')p.stdin.flush()#......do somethingtry: #......do something p.stdout.readline() #......do somethingexcept: print('IOError')#......do something morep.stdin.write('your other command')p.stdin.flush()#......do something more希望本文所述對大家的Python程序設計有所幫助。
新聞熱點
疑難解答
圖片精選