subprocess.Popen() output to logging.StreamHandler()

svensven svensven at gmail.com
Thu Apr 10 14:57:29 EDT 2008


Thomas Dimson wrote:
 > On Apr 10, 8:11 am, "sven _" <svens... at gmail.com> wrote:
 >> My goal is to have stdout and stderr written to a logging handler.
 >> This code does not work:
 >>
 >> # START
 >> import logging, subprocess
 >> ch = logging.StreamHandler()
 >> ch.setLevel(logging.DEBUG)
 >> subprocess.call(['ls', '-la'], 0, None, None, ch, ch)
 >> # END
 >
 > What is wrong with doing something like:
 >
 > import logging, subprocess
 > ch = logging.StreamHandler()
 > ch.setLevel(logging.DEBUG)
 >
 > s = subprocess.Popen( ['ls','-la'], stdout=subprocess.PIPE )
 > while 1:
 >     ch.info( s.stdout.readline() )
 >     if s.poll() == None:
 >         break
 >
 > Perhaps not the most efficient or clean solution, but that is how I
 > usually do it (note: I didn't test the above code).

Thanks, Thomas. That was actually far less messy than I had imagined.
I got it to work -- almost work -- using this code:

import logging, subprocess
logger = logging.getLogger("simple_example")
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - 
%(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)
s = subprocess.Popen(["ping", "-c", "5", "127.0.0.1"], 
stdout=subprocess.PIPE, bufsize=1024)
while s.poll() == None:
     logger.info( s.stdout.readline().strip() )

The problem is that the .poll() seems to be a bit too agressive, so
the while loop will quit before the process actually finishes. In the
ping example above, it will show the pings, but it will skip the
summary at the end.

The response by Vinay Sajip seems to work just fine, though.

Sven




More information about the Python-list mailing list