Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Popen writing to stdin not working when in a thread

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.

like image 392
Violet Avatar asked Feb 24 '23 21:02

Violet


1 Answers

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.

like image 159
Vinay Sajip Avatar answered Feb 26 '23 11:02

Vinay Sajip