Kaia
Kaia

Reputation: 907

Python subprocess Popen readline before closing stdin

import subprocess as sp

p = sp.Popen("/bin/cat", stdin=sp.PIPE, stdout=sp.PIPE)

p.stdin.write(b"foobaz!\n")
p.stdin.close()
print(p.stdout.readline())

This code works as expected (cat echoes the stdin, and we can read the stdout)

If we comment out the p.stdin.close(), the .readline() blocks indefinitely. This behaves the same calling .read(1) instead. Is there a way to readline using the subprocess module without sending EOF to stdin?

I am aware there are other libraries that might solve my problem, and am looking into them as well. For this question, I am only curious if subprocess has this capability, and how to achieve it through subprocess.

Upvotes: 1

Views: 199

Answers (1)

alani
alani

Reputation: 13079

The problem is with the buffering. You can use bufsize=1 if you also use universal_newlines=True (though you would then write strings instead of bytes):

p = sp.Popen("/bin/cat", stdin=sp.PIPE, stdout=sp.PIPE, 
             bufsize=1, universal_newlines=True)
p.stdin.write("foobaz!\n")
print(p.stdout.readline())

The above is tested in Python 3.5.2. Note - I have separately just read an answer to unrelated question that suggests that in more recent Python versions text=True is equivalent of universal_newlines=True, but don't have a more recent installation to try it with at time of writing.

Upvotes: 1

Related Questions