2011-06-15 27 views
4

我試圖編寫一個程序,分別同時讀取和寫入進程的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中有效。

+0

它適用於2.7.1。 – Ravi 2011-06-15 02:34:47

+0

我在3.1.2上,爲什麼它在未來版本中不起作用? – Violet 2011-06-15 02:50:44

回答

6

答案是 - 緩衝。如果您添加一個

proc.stdin.flush() 

撥打proc.stdin.write()後,您會看到「Hello,world!」打印到控制檯(通過子進程),就像你所期望的那樣。

+0

謝謝,完美的作品! – Violet 2011-06-15 14:06:32

+0

謝謝!想知道爲什麼這個工作(沒有刷新)在Py2上,但不是Py3? – 2017-01-01 05:49:37

0

我將proc.stdin.write(文本)更改爲proc.communicate(text),並且在Python 3.1中起作用。

+1

我不想使用'communicate()',因爲有一個並行線程處理程序的stdout。我需要獨立讀寫。 – Violet 2011-06-15 03:36:05

+0

proc.communicate(text)[1]怎麼樣? – Ravi 2011-06-15 03:47:56

+1

'溝通()'讀取直到文件結束,無論如何,這是爲了保持運行。這不僅僅是我會交流的一次。 – Violet 2011-06-15 04:06:05

相關問題