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"],
follow = s.stdout
while s.poll() == None:
mess = follow.readline()
if mess:
print mess.strip()

ret = s.wait()

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

And then go weeee!