Doo Dah
Doo Dah

Reputation: 4029

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

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?

Upvotes: 10

Views: 10480

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122172

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)

Upvotes: 26

Related Questions