Python Popen在线程中写入stdin时不工作
我正在尝试编写一个程序,分别同时读取和写入进程的std(out/in)。然而,在线程中写入程序的stdin似乎不起作用。以下是相关的代码位:Python Popen在线程中写入stdin时不工作,python,multithreading,subprocess,Python,Multithreading,Subprocess,我正在尝试编写一个程序,分别同时读取和写入进程的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"
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上运行Python3.1.2,确认它在python2.7中工作。我将proc.stdin.write(text)更改为proc.communicate(text),这在Python3.1中工作。答案是-缓冲。如果你加一个
proc.stdin.flush()
调用
proc.stdin.write()
后,您将看到控制台(由子进程)打印出“Hello,world!”,正如您所期望的那样。我使用的是3.1.2,为什么它在将来的版本中不起作用呢?我不想使用communicate()
,因为有一个并行线程处理程序的stdout。我需要独立读写。communicate()
一直读到文件末尾,这意味着要保持运行。这不是我唯一的一次交流。谢谢!想知道为什么这在Py2上有效(没有刷新),而在Py3上无效?