我試圖編寫一個程序,分別同時讀取和寫入進程的std(out/in)。但是,似乎在一個線程中寫入程序的stdin不起作用。這裏是相關的代碼位:Python Popen寫入到標準輸入不能在線程中工作
import subprocess, threading, queue
def intoP(proc, que):
while True:
if proc.returncode is not None:
break
text = que.get().encode() + b"\n"
print(repr(text)) # This works
proc.stdin.write(text) # This doesn't.
que = queue.Queue(-1)
proc = subprocess.Popen(["cat"], stdin=subprocess.PIPE)
threading.Thread(target=intoP, args=(proc, que)).start()
que.put("Hello, world!")
怎麼回事,有沒有辦法解決它?
我在Mac OSX上運行python 3.1.2,它確認它在python2.7中有效。
它適用於2.7.1。 – Ravi 2011-06-15 02:34:47
我在3.1.2上,爲什麼它在未來版本中不起作用? – Violet 2011-06-15 02:50:44