Vio*_*let 4 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"
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!")
Run Code Online (Sandbox Code Playgroud)
出了什么问题,有没有办法解决它?
我在Mac OSX上运行python 3.1.2,它确认它在python2.7中运行.
答案是 - 缓冲.如果你添加一个
proc.stdin.flush()
Run Code Online (Sandbox Code Playgroud)
proc.stdin.write()通话结束后,你会看到"Hello,world!" 正如您所期望的那样,打印到控制台(通过子进程).