Python Popen writes that stdin doesn't work when in a stream

I am trying to write a program that simultaneously reads and writes to the std (out / in) process, respectively. However, it seems that writing to the stdin program in the stream does not work. Here are the relevant code bits:

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 is going wrong and is there a way to fix it?

I am running python 3.1.2 on Mac OSX, it confirmed that it works in python2.7.

+4
source share
2 answers

The answer is buffering. If you add

 proc.stdin.flush() 

after calling proc.stdin.write() you will see "Hello world!". printed to the console (by sub-process), as expected.

+6
source

I changed proc.stdin.write (text) to proc.communicate (text) and it works in Python 3.1.

0
source

All Articles