Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subprocess.call logger info and error for stdout and stderr respectively

Tags:

python

logging

I have a logger. something like this:

import logging

logger = logging.getLogger('myApp')
hdlr = logging.FileHandler('myApp.log')
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)

I am calling an external process like this:

subprocess.call("someCommand")

I want to capture stdout and stderr seperatly from that process so that I can log them acccordingly. For example

logger.info(<stdout>)
logger.error(<stderr>)

I see various ways to capture all of the subprocess in one stream. But, if there is an actual error, I would like to log it as such. Is there a way to do that?

like image 738
Doo Dah Avatar asked Sep 12 '13 21:09

Doo Dah


1 Answers

Use subprocess.Popen() and call .communicate() on the returned process object:

p = subprocess.Popen(["someCommand"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()

if stdout:
    logger.info(stdout)
if stderr:
    logger.error(stderr)
like image 66
Martijn Pieters Avatar answered Nov 14 '22 03:11

Martijn Pieters