如何在 Python 中为 argparse 设置自定义输出处理程序? [英] How to set custom output handlers for argparse in Python?
问题描述
我已将 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.
这很容易通过将 FileHandler
添加到您的 logging
对象来实现.轻轻松松.
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
.
可以吗?怎么样?
推荐答案
看argparse.py 源代码 似乎没有办法配置这种行为.
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屋!