Python Popen writing to stdin not working when in a thread
I'm trying to write a 开发者_运维问答program that simultaneously reads and writes to a process's std(out/in) respectively. However, it seems that writing to a program's stdin in a thread does not work. Here's the relevant bits of code:
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!")
What's going wrong, and is there a way to fix it?
I'm running python 3.1.2 on Mac OSX, it's confirmed that it works in python2.7.
The answer is - buffering. If you add a
proc.stdin.flush()
after the proc.stdin.write()
call, you'll see "Hello, world!" printed to the console (by the subprocess), as you'd expect.
I changed proc.stdin.write(text) to proc.communicate(text), and that works in Python 3.1.
精彩评论