Thursday, February 22, 2007

python subprocess.Popen - instant (unbuffered) command output

Did you ever wanted to know how to call a process from Python and get the output instantly, instead of waiting for the execution to finish?

Try this:
import os
import sys
import subprocess

s = subprocess.Popen(["tail", "/tmp/wee", "-f"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
follow = s.stdout
while s.poll() == None:
mess = follow.readline()
if mess:
print mess.strip()

ret = s.wait()
sys.exit(0)

Now go ahead and type in another terminal: echo PRINTME >> /tmp/wee

And then go weeee!