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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.