Here's a few things I tried to write output to a python subprocess pipe.
from subprocess import Popen, PIPE
p = Popen('less', stdin=PIPE)
for x in xrange(100):
p.communicate('Line number %d.\n' % x)This seemed like the most obvious solution but it fails miserably. It seems that the first call to communicate also closes the pipe and the second loop raises an exception.
from subprocess import Popen, PIPE
p = Popen('less', stdin=PIPE)
for x in xrange(100):
p.stdin.write('Line number %d.\n' % x)This is expressly stated to be a bad idea in the docs, but it works - sort of. I get some weird behavior. There's no call to p.wait() (which communicate does by default) so anything after the loop runs before the subproccess (less in this case) is closed. Adding a call to wait after the loop causes even weirder behavior.
from subprocess import Popen, PIPE
out = []
p = Popen('less', stdin=PIPE)
for x in xrange(100):
out.append('Line number %d.' % x)
p.communicate('\n'.join(out))This works great! We only have one call to communicate and that calls wait properly. Unfortunately, we have to create the entire output in memory before writing any of it out. At least it works.
Thanks for sharing that! Very useful.