萬盛學電腦網

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

Python subprocess.Popen 管道互動:啟動子程序、寫入 stdin、讀取 stdout

核心類別 subprocess.Popen

取代舊式 os.popen/commands,提供完整的進程控制與管道管理。

雙向管道範例:駕馭 cat -n 加行號


from subprocess import Popen, PIPE

p = Popen(["cat", "-n"], stdin=PIPE, stdout=PIPE, bufsize=1, universal_newlines=True)
fin, fout = p.stdin, p.stdout

for i in range(10):
    fin.write(f"line{i}\n")
    fin.flush()
    print(fout.readline().rstrip())

fin.close()
fout.close()
p.wait()

關鍵參數

參數說明
args指令與參數列表(建議用 list 避免 shell 注入)
stdin/stdout/stderrPIPE 建立管道,None 繼承,檔案物件重導向
bufsize0 無緩衝,1 行緩衝,>1 塊緩衝,-1 系統預設
universal_newlinesTrue 以文字模式處理(Python 3.7+ 用 text=True)
shellTrue 經由 shell 執行(有注入風險)
cwd/env工作目錄、環境變數

高階 API:subprocess.run (Python 3.5+)


result = subprocess.run(
    ["grep", "pattern", "file.txt"],
    capture_output=True, text=True, timeout=5
)
print(result.stdout)
print(result.returncode)

常見坑與解法

  • 死結:雙向管道若雙方同時等待對方 → 用執行緒分別讀寫,或改用 asyncio.subprocess
  • 大量輸出:管道緩衝區滿導致阻塞 → 串流處理、增大 bufsize、或寫入暫存檔
  • 編碼錯誤:明確指定 encoding='utf-8', errors='replace'
  • 殭屍進程:務必呼叫 wait() 或 communicate() 回收

非同步版本 (Python 3.7+)


import asyncio

async def run_cat():
    proc = await asyncio.create_subprocess_exec(
        'cat', '-n',
        stdin=asyncio.subprocess.PIPE,
        stdout=asyncio.subprocess.PIPE
    )
    for i in range(5):
        proc.stdin.write(f"line{i}\n".encode())
        await proc.stdin.drain()
        line = await proc.stdout.readline()
        print(line.decode().rstrip())
    proc.stdin.close()
    await proc.wait()
copyright © 萬盛學電腦網 all rights reserved