管道python记录stdout流输出到grep [英] pipe python logging stdout stream output to grep

查看:152
本文介绍了管道python记录stdout流输出到grep的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很早就知道了这个原因,但此后我就已经忘记了,并且在5分钟的谷歌搜索中没有找到答案.

I knew the reason for this a while back but I have since forgotten and 5 mins of googling hasn't revealed the answer.

我写了一个有两个处理程序的python脚本.一种用于文件,另一种用于流.

I have written a python script which has two handlers. One for files and one for streams.

一切都如我所愿.

现在,我想快速grep查找正在输出到终端的输出中的某些内容,但是通过grep传递脚本输出的管道似乎无法正常工作,因为所有输出仍会打印到终端上.

Now, I wanted to quickly grep for something in the output that was being printed to the terminal but piping the script's output through grep doesn't appear to be working in that all of the output still get's printed to the terminal.

我正在使用Unix和python 2.7

I am using unix and python 2.7

这可能是一个重复的问题,但我找不到答案.

This is probably a duplicate question but I can't find the answer.

这是我的日志记录模块设置:

Here's my setup of the logging module:

def setup_logger(verbosity):
    #logger = logging.getLogger(regress.app_name)
    logger = logging.getLogger('components')
    logger.setLevel(logging.DEBUG)
    # create file handler which logs even debug messages
    fh = logging.FileHandler(Config.logging_file_name, mode='w')
    fh.setLevel(logging.DEBUG)
    # create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel({True:logging.DEBUG, False:logging.INFO}[verbosity])
    # create formatter and add it to the handlers
    file_formatter = logging.Formatter('%(asctime)s - %(pathname)s - %(funcName)s - %(name)s - %(levelname)s - %(lineno)s - %(message)s')

    console_formatter = logging.Formatter('%(filename)s - %(lineno)s - %(levelname)s - %(message)s')
    fh.setFormatter(file_formatter)
    ch.setFormatter(console_formatter)
    # add the handlers to the logger
    logger.addHandler(fh)
    logger.addHandler(ch)

    #logging.abort = abort
    #logging.abort("testing...")
    #logger.info("does this happen?")

    #logging.func = func
    #logging.func()
    #logger.func()

我对脚本的调用如下:

<script_name> <script args> | grep -i <search_string>

推荐答案

正如@Blender在原始问题下方的注释中所述,您只需要重定向stderr.您可以通过在管道之前添加2>&1重定向来做到这一点.因此,例如

As @Blender mentions in the comments below the original question, you just need to redirect stderr. You can do this by adding a 2>&1 redirect before the pipe. So, for example,

python main.py 2>&1 | grep INFO

将过滤main.py记录的任何INFO行.

这篇关于管道python记录stdout流输出到grep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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