How to set custom output handlers for argparse in Python?

后端 未结 3 1202
不思量自难忘°
不思量自难忘° 2021-02-15 17:31

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.

Tha

3条回答
  •  悲&欢浪女
    2021-02-15 18:14

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

    My suggestion(s) would be:

    • File a bug report with a patch :)

    Override/patch:

    • print_* method(s)
    • error method.

    The print_* method(s) seem to take an optional file argument which defaults to _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()
    

提交回复
热议问题