萬盛學電腦網

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

Python subprocess 進程間通訊:Popen 管道實現父子進程雙向資料交換

subprocess.Popen 配合 stdin=PIPE、stdout=PIPE、stderr=PIPE 可建立父子進程雙向通訊管道。本文提供最小化雙腳本範例,示範父進程寫入、子進程讀取、父進程收集輸出的完整流程。

父進程 a.py

import subprocess, time

subproc = subprocess.Popen(
    ['c:/python31/python.exe', 'c:/b.py'],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    shell=True
)

time.sleep(0.5)           # 等待子進程啟動
print('start')
subproc.stdin.write(b'datan')
subproc.stdin.flush()

# 方式一:communicate() 一次性收集(會關閉 stdin)
stdout_data, stderr_data = subproc.communicate(b'datan')
print('stdout:', stdout_data.decode())
print('stderr:', stderr_data.decode())
print('end')

子進程 b.py

import sys
print('receive...', file=sys.stderr)
s = sys.stdin.readline()
print('get:', len(s), s.strip(), file=sys.stderr)
sys.stdout.write('child echo: ' + s)

關鍵細節提醒

  • stdin.write() 需傳入 bytes(Python 3),寫入後必須 flush()
  • communicate() 會關閉 stdin、等待進程結束並回傳 (stdout, stderr);若需互動式多輪通訊,請直接操作 stdin/stdout 物件
  • shell=True 允許字串命令,但有注入風險;生產環境建議傳列表 ['python', 'b.py']
  • 跨平台路徑:使用 sys.executable 取得當前 Python 解譯器路徑
  • 大量資料交換考慮 multiprocessing.Connection 或 socket 替代管道

非阻塞讀取進階模式

import select, fcntl, os

# 設定 stdout 非阻塞
flags = fcntl.fcntl(subproc.stdout.fileno(), fcntl.F_GETFL)
fcntl.fcntl(subproc.stdout.fileno(), fcntl.F_SETFL, flags | os.O_NONBLOCK)

while subproc.poll() is None:
    ready, _, _ = select.select([subproc.stdout], [], [], 0.1)
    if ready:
        print(subproc.stdout.read().decode(), end='')
copyright © 萬盛學電腦網 all rights reserved