標籤:進程id line 使用 blog 子進程 ret none order output
subprocess 模組可以使 Python 執行外部命令(Linux)和程式(exe),並得到相應的輸出結果,進一步處理。在 Python3.5 中,subprocess 模組取代了 os.system、os.spawn* 。該模組很好地體現了 Python 膠水語言的特性,豐富了 Python 的拓展能力,故本文接下來主要介紹 subprocess 模組的用法,並簡單說明在 Python2/3 中的使用區別。
速查表
|
Python2 |
Python3.5 |
|
subprocess.call(...) |
subprocess.run(...) |
|
subprocess.check_call(...) |
subprocess.run(..., check=True) |
|
subprocess.check_output(...) |
subprocess.run(..., check=True, stdout=PIPE).stdout |
|
subprocess.Popen(...) |
subprocess.Popen(...) |
通過上表可以看到,在 Python2 中 subprocess 模組共有三個函數 call、check_call、check_output 和一個類 Popen ,本質上這三個函數都是基於類 Popen 的封裝,可以更簡單地執行程式和獲得輸出。而在 Python3.5 中,三個函數可以通過 run 函數和參數設定來使用,同時這三個函數也可以在 Python3.5 中使用。
執行外部命令和程式
1 import subprocess 2 subprocess.call(["ls", "-l"]) 3 subprocess.call("ls -l", shell=True) 4 subprocess.call("ffmpeg.exe -i test3.mp4 test.avi", shell=True)
前兩個 call() 執行了查看目前的目錄的命令,第三個 call() 調用了 ffmpeg.exe 程式,對 test3.mp4 進行轉碼,產生 test.avi 。call() 函數預設接收拆分命令的列表,執行成功後,傳回值 returncode 為0,失敗返回1。當參數 shell=True 時,接收字串,運行 shell,通過 shell 解釋字串,執行外部命令和程式。
添加錯誤處理的執行
1 subprocess.check_call("exit 1", shell=True)
check_call() 函數與 call() 函數用法相似。但當傳回值不為0時,會拋出 subprocess.CalledProcessError 異常。
擷取輸出的執行
1 subprocess.check_output("ls -t | head -n 4", shell=True)
check_output() 函數與 check_call() 函數用法相似。但會返回執行的輸出結果,以 bytes 序列接收,在 Python3 中可進行相應的解碼 decode() 成字串 str 序列,再進一步處理。該範例返回目前的目錄下按時間排序的前四個檔案的詳細資料。
需求化的執行
1 child1 = subprocess.Popen("ls -t", shell=True, stdout=subprocess.PIPE) 2 child2 = subprocess.Popen("head -n 4", shell=True, stdin=child1.stdout, stdout=subprocess.PIPE) 3 outs, errs = child2.communicate()
Popen() 類建立並執行子進程。通過參數 stdin, stdout, stderr 改變標準輸入、標準輸出、標準錯誤,使用 subprocess.PIPE 初始化參數,建立緩衝區,傳遞文字資料流,實現 Shell 管道功能。通過 communicate() 方法阻塞父進程,擷取子進程執行結果,以 bytes 序列返回輸出和錯誤的元組。
還可通過下列方法,操作子進程,擷取相關資訊:
- Popen.wait():阻塞父進程,等待子進程終止。返回屬性 returncode 。
- Popen.poll():檢查子進程狀態。返回屬性 returncode 。
- Popen.kill():殺死子進程。
- Popen.pid:擷取子進程的進程ID。
- Popen.returncode:擷取子進程的返回碼。
官方文檔
Python3中的subprocess
Python2中的subprocess
Python2/3 中執行外部命令(Linux)和程式(exe) -- 子進程模組 subprocess