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

Thomas Dimson tdimson at gmail.com
Thu Apr 10 16:41:53 EDT 2008


On Apr 10, 3:05 pm, svensven <svens... at gmail.com> wrote:
> 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

I think what I actually meant was:

s = subprocess.Popen( ['ls','-la'], stdout=subprocess.PIPE )
while 1:
    line = s.stdout.readline()
    if not line:
        break
    logging.info( line )

The problem with p.poll() is that the process probably has ended
before you have gotten all the text out of the buffer. Readline will
return a falsy value when the process ends.

Anyway, this post has a lot of responses so I'm sure _something_
works :)



More information about the Python-list mailing list