在 Python 中呼叫外部 Shell 指令並捕獲其輸出,是系統管理、自動化腳本開發的常見需求。標準庫 subprocess 模組提供了強大且靈活的介面,本文透過實際範例示範如何正確取得命令的標準輸出、錯誤輸出及返回碼。
#!/usr/bin/python
import subprocess
# 呼叫 date 指令,導向標準輸出管道
p = subprocess.Popen("date", stdout=subprocess.PIPE, shell=True)
# 與子進程互動:讀取 stdout/stderr,等待進程結束
# communicate() 會回傳 (stdout_data, stderr_data) 元組
(output, err) = p.communicate()
# 取得進程返回碼
p_status = p.wait()
print "Command output : ", output
print "Command exit status/return code : ", p_status
| 方法/屬性 | 說明 |
|---|---|
Popen() | 建立子進程,stdout=PIPE 讓我們能讀取輸出 |
communicate() | 一次性讀取所有輸出並等待進程結束,避免死鎖風險 |
wait() | 等待進程結束並取得返回碼(0 通常代表成功) |
shell=True | 透過 Shell 解析命令,支援管道、重導向等 Shell 功能 |
communicate(input=b'data')subprocess.run() 更簡潔的高階 API.decode('utf-8'))原文出處:Python run external command and get output