萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 執行 Linux 指令完整指南:subprocess 模組最佳實踐

推薦方式:subprocess.run (Python 3.5+)

統一介面、支援超時、自動檢查返回碼、擷取輸出。

基本用法

import subprocess

# 簡單執行,拋出例外若失敗
result = subprocess.run(["ls", "-l"], check=True, text=True, capture_output=True)
print(result.stdout)

# 等同舊版 call/check_call/check_output

進階參數詳解

參數說明常用值
args指令與參數列表 (推薦) 或字串["ls", "-l"] 或 "ls -l" (需 shell=True)
shell是否經由 Shell 執行 (支援管線、重導向、通配符)False (預設, 安全) / True (需輸入消毒)
capture_output擷取 stdout/stderr (3.7+)True
text / universal_newlines以字串而非位元組處理 I/OTrue
encoding指定編碼"utf-8"
timeout秒數,超時拋出 TimeoutExpired30
check非零返回碼拋出 CalledProcessErrorTrue
cwd工作目錄"/home/user"
env環境變數字典 (None=繼承父程序){**os.environ, "MY_VAR": "val"}
input傳遞給 stdin 的資料"data\n"

常見模式範例

1. 管線串接 (shell=True 風險 vs Popen 管線)

# ❌ 風險:shell injection
subprocess.run("cat file.txt | grep error", shell=True, check=True)

# ✅ 安全:Popen 管線
p1 = subprocess.Popen(["cat", "file.txt"], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["grep", "error"], stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close()  # 允許 p1 收到 SIGPIPE
output = p2.communicate()[0]

2. 即時逐行讀取輸出 (長時間執行指令)

proc = subprocess.Popen(
    ["ping", "google.com"],
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
    text=True,
    bufsize=1  # 行緩衝
)
for line in proc.stdout:
    print(f"[LOG] {line.rstrip()}")
proc.wait()

3. 背景執行 + 稍後輪詢結果

proc = subprocess.Popen(["./long_task.sh"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# 做其他事...
try:
    stdout, stderr = proc.communicate(timeout=60)
except subprocess.TimeoutExpired:
    proc.kill()
    stdout, stderr = proc.communicate()

4. 處理互動式指令 (需 pty)

# 使用 pexpect 或 pty 模組
import pexpect
child = pexpect.spawn("ssh user@host")
child.expect("password:")
child.sendline("mypassword")
child.expect("# ")
child.sendline("ls -l")
child.expect("# ")
print(child.before.decode())

舊版 API 對照 (Python 3.4 及之前)

舊函數對應 subprocess.run 寫法
subprocess.call(cmd)run(cmd, check=False).returncode
subprocess.check_call(cmd)run(cmd, check=True)
subprocess.check_output(cmd)run(cmd, check=True, capture_output=True).stdout
Popen(cmd).wait()run(cmd).returncode

安全性鐵律

  1. **預設使用列表形式 args**,避免 shell=True。
  2. 若必須 shell=True,**嚴格驗證/轉義使用者輸入** (shlex.quote)。
  3. 避免在指令中嵌入密碼,改用環境變數或金鑰檔。
  4. 限制子程序權限:preexec_fn=os.setsid、user/group (Unix)。

除錯技巧

# 印出實際執行指令
print("EXEC:", " ".join(shlex.quote(a) for a in cmd_list))

# 完整捕獲錯誤資訊
try:
    subprocess.run(cmd, check=True, capture_output=True, text=True, timeout=10)
except subprocess.CalledProcessError as e:
    print(f"Exit code: {e.returncode}")
    print(f"Stdout: {e.stdout}")
    print(f"Stderr: {e.stderr}")
except subprocess.TimeoutExpired as e:
    print(f"Timeout after {e.timeout}s")
    print(f"Partial output: {e.stdout}")
copyright © 萬盛學電腦網 all rights reserved