用子进程调用的程序-记录器消息不打印? [英] Program called with subprocess - logger messages are not printed?

查看:62
本文介绍了用子进程调用的程序-记录器消息不打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果通过子进程调用该程序,则从程序的记录器获取消息是一个问题.

there's a problem getting messages from a program's logger, if this program is called with subprocess.

以下是BooFoo.py程序,该程序使用logger将消息打印到文件和控制台窗口:

Here's the program BooFoo.py that uses logger to print messages to a file and console window:

import logging
LOG_FILENAME = 'example.log'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
logger = logging.getLogger('main')
logger.addHandler(logging.StreamHandler())
print 'print foo'
logger.info('logger boo')

这是程序CallBooFoo.py:

Here's the program CallBooFoo.py:

import subprocess
proc = subprocess.Popen(['python BooFoo.py'], bufsize=512, stdin = None, 
     stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell=True)
proc_out, proc_err = proc.communicate()
print proc_out

"logger boo"未随CallBooFoo.py打印.任何想法如何解决这个问题?使用os.system是可以的,但是由于其他一些原因,它不是解决方案.

"logger boo" does not get printed with CallBooFoo.py. Any idea how to fix this? Using os.system works, but is not a solution due to some other reasons.

推荐答案

logging.StreamHandler 默认为写入标准错误,而不是标准输出.您可以改为使用 logging.StreamHandler(sys.stdout)将其更改为标准输出.

logging.StreamHandler defaults to writing to standard error, not standard output. You can change this to standard output by using logging.StreamHandler(sys.stdout) instead.

您还可以按原样保留代码,并在调用过程中打印 proc_err 的值,而不是(或附加) proc_out .这将显示子进程的标准错误.

You can also keep your code as is, and print the value of proc_err instead of (or in addition to) proc_out in the calling process. This will show the standard error of the child process.

如果需要将stdout和stderr混合在一起,可以将调用过程更改为:

If you need to see both stdout and stderr mixed together, you can change the calling process to:

proc = subprocess.Popen(['python BooFoo.py'], bufsize=512, stdin = None, 
     stdout = subprocess.PIPE, stderr = subprocess.STDOUT, shell=True)
proc_out, proc_err = proc.communicate()
print proc_out

这篇关于用子进程调用的程序-记录器消息不打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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