萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 編程語言綜合 >> Python中subprocess模塊用法實例詳解

Python中subprocess模塊用法實例詳解

   本文實例講述了Python中subprocess模塊用法。分享給大家供大家參考。具體如下:

  執行命令:

  ?

1 2 3 4 >>> subprocess.call(["ls", "-l"]) 0 >>> subprocess.call("exit 1", shell=True) 1

  測試調用系統中cmd命令,顯示命令執行的結果:

  ?

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

  測試在python中顯示文件內容:

  ?

1 2 3 4 5 y=subprocess.check_output(["type", "app2.cpp"],shell=True) print(y) #include <iostream> using namespace std; ......

  查看ipconfig -all命令的輸出,並將將輸出保存到文件tmp.log中:

  ?

1 2 handle = open(r'd:tmp.log','wt') subprocess.Popen(['ipconfig','-all'], stdout=handle)

  查看網絡設置ipconfig -all,保存到變量中:

  ?

1 2 3 4 5 6 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):

  ?

1 2 3 4 5 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 298n', None)

  如果想頻繁地和子線程通信,那麼不能使用communicate();因為communicate通信一次之後即關閉了管道.這時可以試試下面的方法:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 p= subprocess.Popen(["wc"], stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True) p.stdin.write('your command') p.stdin.flush() #......do something try: #......do something p.stdout.readline() #......do something except: print('IOError') #......do something more p.stdin.write('your other command') p.stdin.flush() #......do something more

  希望本文所述對大家的Python程序設計有所幫助。

copyright © 萬盛學電腦網 all rights reserved