我正在尝试编写一个程序,分别同时读取和写入进程的std(out / in)。但是,似乎在线程中写入程序的stdin不起作用。这是相关的代码:
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 :(得分:7)
答案是 - 缓冲。如果添加
proc.stdin.flush()
在proc.stdin.write()
电话结束后,您会看到“Hello,world!”打印到控制台(通过子进程),正如您所期望的那样。
答案 1 :(得分:0)
我将proc.stdin.write(text)更改为proc.communicate(text),这在Python 3.1中有效。