萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

Python 捕獲 Shell/Bash 腳本輸出結果實戰範例

前言

在 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')
  • Python 3.5+ 建議改用 subprocess.run() 更簡潔的高階 API
  • 處理二進位資料時注意編碼轉換(.decode('utf-8'))
  • 長時間運行的進程可考慮非阻塞讀取或執行緒處理

參考資源

原文出處:Python run external command and get output

copyright © 萬盛學電腦網 all rights reserved