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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With