我想用Python加載外部命令行程序並通過管道與它進行通信。該程序通過stdin接受文本輸入,並將行輸出爲stdout。通信應該使用select()進行異步。Python:select()不發信號通知管道的所有輸入
問題是,並不是所有的程序輸出都以select()方式發出信號。通常最後一行或兩行不發送信號。如果select()以超時返回,並且我試圖從管道讀取readline(),則立即返回程序發送的行。見下面的代碼。
該程序不緩衝輸出並以文本行發送所有輸出。通過許多其他語言和環境中的管道連接到程序迄今運行良好。
我在Mac OSX 10.6上試過Python 3.1和3.2。
import subprocess
import select
engine = subprocess.Popen("Engine", bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
engine.stdin.write(b"go\n")
engine.stdin.flush()
while True:
inputready,outputready,exceptready = select.select([engine.stdout.fileno()] , [], [], 10.0)
if (inputready, outputready, exceptready) == ([], [], []):
print("trying to read from engine anyway...")
line = engine.stdout.readline()
print(line)
for s in inputready:
line = engine.stdout.readline()
print(line)
完美的作品,謝謝! – StefanMK 2011-03-30 20:11:50
很高興能幫到你! – samplebias 2011-03-31 00:57:49