using subprocess for non-terminating command

Jerry Hill malaclypse2 at gmail.com
Wed Jul 4 23:30:54 EDT 2007


On 7/4/07, O.R.Senthil Kumaran <orsenthil at users.sourceforge.net> wrote:
> Only when the program has executed and the output available, subprocess can
> read through PIPE's stdout it seems ( not at any other time).
> With killing, I loose the output.

I think you have to read the data from the process's stdout before you
kill it.  If you want to process the output of the program before it's
done, do something like this:

import subprocess
process = subprocess.Popen("ping 127.0.0.1", stdout=subprocess.PIPE, shell=True)
for i in xrange(10):
        line = process.stdout.readline()
        print "line:", repr(line)

Then you can decide to kill the subprocess when you have enough data,
or whatever.

Also, even though the output from ping appears to be pretty easy to
read, there can be problems with buffering when you connect a pipe to
the stdout of some programs.  The pexpect faq talks a little bit about
that - http://pexpect.sourceforge.net/#faq .  If you're working under
a unix system, pexpect is really useful for automating interactive
programs that are otherwise difficult to work with.

-- 
Jerry



More information about the Python-list mailing list