subprocess模塊是2.4版本中新增的模塊, 它容許您生成新進程,鏈接到它們的 輸入/輸出/錯誤 管道,並得到它們的返回碼(狀態信息), 該模塊的目的在於取代幾個較舊的模塊和功能html
官方文檔 : https://docs.python.org/2/library/subprocess.html?highlight=subprocess#module-subprocesspython
subprocess 模塊能夠用於執行系統命令, 拿到執行的結果, 速度比較的快, 而且它容許你建立一個新的進程讓其去執行另外的程序, 並與它進行通訊,獲取標準的輸入、標準輸出、標準錯誤以及返回碼等linux
import subprocess res = subprocess.Popen( "dir", # 在終端運行的命令 shell=True, # 新開一個終端 stdout=subprocess.PIPE, # 執行完命令, 將正確輸出放到一個管道里 stderr=subprocess.PIPE, # 將錯誤輸出放到一個管道里 ) result = res.stdout.read() # 拿到的是 bytes 格式的字符 result= str(result,encoding="gbk") # 在windows須要使用gbk編碼,linux和mac上是"utf-8" print(result)
import subprocess res = subprocess.Popen( "aaa", # 在終端運行的命令 shell=True, # 新開一個終端 stdout=subprocess.PIPE, # 執行完命令, 將正確輸出放到一個管道里 stderr=subprocess.PIPE, # 將錯誤輸出放到一個管道里 ) result = res.stderr.read() # 拿到的是 bytes 格式的字符 result= str(result,encoding="gbk") # 在windows須要使用gbk編碼 print(result)
import subprocess res1 = subprocess.Popen( # 開啓的第一的進程 "dir", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) res2 = subprocess.Popen( # 開啓的第二個進程 "findstr html*", shell=True, stdin=res1.stdout, # 將第一個進程的正確輸出結果拿到作處理 stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) result = res2.stdout.read() result= str(result,encoding="gbk") print(result)
|
管道符號能夠實現將第一個命令的結果傳遞給第二個命令使用import subprocess res1 = subprocess.Popen( "dir | findstr html*", # 使用管道符號運行命令 shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) result = res1.stdout.read() result= str(result,encoding="gbk") print(result)