萬盛學電腦網

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

Python subprocess 模組完整實戰:執行命令、管道、即時互動

subprocess 是 Python 3 推薦的子程序管理模組,取代舊有 os.system、os.popen、commands 等,提供豐富的進程控制、管道串聯與即時 I/O 能力。

基礎執行

import subprocess
subprocess.call(["ls", "-l"])           # 返回退出碼
subprocess.call("exit 1", shell=True)   # shell 指令,返回 1

捕獲輸出

# 簡單捕獲標準輸出
output = subprocess.check_output(["echo", "Hello World!"], shell=True)
print(output.decode())  # b'Hello World!\n'

# 讀取檔案內容(Windows type 指令)
content = subprocess.check_output(["type", "app2.cpp"], shell=True)

重導向至檔案

with open('tmp.log', 'w') as f:
    subprocess.Popen(['ipconfig', '/all'], stdout=f)

捕獲至變數並解析

proc = subprocess.Popen(['ipconfig', '/all'], stdout=subprocess.PIPE, shell=True)
stdout, stderr = proc.communicate()
print(stdout.decode())

管道串聯(模擬 shell pipe)

child1 = subprocess.Popen(["dir", "/w"], stdout=subprocess.PIPE, shell=True)
child2 = subprocess.Popen(["find", "txt"], stdin=child1.stdout, stdout=subprocess.PIPE, shell=True)
out, _ = child2.communicate()
print(out.decode())

即時互動(非通信一次性)

p = subprocess.Popen(["cmd"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, text=True)
p.stdin.write("dir\n")
p.stdin.flush()
print(p.stdout.readline())
p.stdin.write("exit\n")
p.stdin.flush()

最佳實踐建議

  • 優先使用 subprocess.run()(Python 3.5+)簡化常見情況。
  • 避免 shell=True 除非需要 shell 特性(通配符、管道、環境變數展開),防止注入風險。
  • 長時間運行或大量輸出的子進程,使用 Popen + 執行緒/非阻塞 I/O 避免死鎖。
  • Windows 下 text=True(或 universal_newlines=True)自動處理編碼與換行。
copyright © 萬盛學電腦網 all rights reserved