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

svensven svensven at gmail.com
Thu Apr 10 15:05:20 EDT 2008


Vinay Sajip wrote:
 > On Apr 10, 1:11 pm, "sven _" <svens... at gmail.com> wrote:
 >> My goal is to have stdout and stderr written to a logginghandler.
 >
 > Thomas was almost right, but not quite - you can't call info on a
 > Handler instance, only on a Logger instance. The following script:

Yes, but that was easily fixed. Still there seemed to be a problem
there with the .poll(), since it would think the process ended while
it was actually running. The result was that only some of the command
output was shown.

 > import logging
 > import subprocess
 >
 > logging.basicConfig(level=logging.INFO) # will log to stderr of this
 > script
 >
 > s = subprocess.Popen( ['ls','-la'], stdout=subprocess.PIPE )
 > while 1:
 >     line = s.stdout.readline()
 >     exitcode = s.poll()
 >     if (not line) and (exitcode is not None):
 > 	break
 >     line = line[:-1]
 >     logging.info("%s", line)

This works perfectly, as far as I can tell. You seem to use another
conditional, though.

I'll take a closer look at this tomorrow. Thanks for the clean
solution, Vinay.

sven



More information about the Python-list mailing list