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