如何在Python中为argparse设置自定义输出处理程序? [英] How to set custom output handlers for argparse in Python?

查看:111
本文介绍了如何在Python中为argparse设置自定义输出处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将logger配置为同时打印到终端stdout和文件上,以便可以保存我可以参考的日志消息存档.

I have configured logger to print both onto terminal stdout and to a file so I can have an archive of logging messages that I can refer to.

通过在您的logging对象中添加FileHandler可以轻松实现.轻松自在.

That is easily accomplished by adding a FileHandler to your logging object. Easy peasy.

我现在要完成的工作是在遇到解析错误时,也将argparse日志记录到同一个文件中,并将日志记录到stdout中.到目前为止,它仅打印到stdout.我查看了argparse 文档,但找不到任何有关设置的信息argparse的其他输出流或管道.

What I want to accomplish now is to make argparse log also to the same file along with logs to stdout when it encounters parsing errors. So far it only prints to stdout. I looked in the argparse documentation but I can't find anything about setting a different output stream or pipe for argparse.

有可能吗?怎么样?

推荐答案

查看

Looking at the argparse.py source code there doesn't seem to be a way to configure this behaviour.

我的建议是:

  • 提交带有修补程序的错误报告:)

覆盖/修补程序:

  • print_*方法
  • error方法.
  • print_* method(s)
  • error method.

print_*方法似乎采用了可选的file参数,默认为_sys.stdout.

The print_* method(s) seem to take an optional file argument which defaults to _sys.stdout.

更新:或者,您可以执行以下操作,从而在解析参数时临时重定向sys.stdout:

Update: Alternatively you could do something like this whereby you redirect sys.stdout temporarily while you parse arguments:

from contextlib import contextmanager

@contextmanager
def redirect_stdout_stderr(stream):
    old_stdout = sys.stdout
    old_stderr = sys.stderr
    sys.stdout = stream
    sys.stderr = stream
    try:
        yield
    finally:
        sys.stdout = old_stdout
        sys.stderr = old_stderr


with redirct_stdout_stderr(logstream):
    args = parser.parse_args()

这篇关于如何在Python中为argparse设置自定义输出处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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