subprocess.call记录器信息和stdout和stderr的错误 [英] subprocess.call logger info and error for stdout and stderr respectively

查看:358
本文介绍了subprocess.call记录器信息和stdout和stderr的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个记录器.像这样的东西:

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")

我想从该过程中分别捕获stdout和stderr,以便可以相应地记录它们.例如

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?

推荐答案

使用subprocess.Popen()并在返回的过程对象上调用.communicate():

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)

这篇关于subprocess.call记录器信息和stdout和stderr的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆