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.
That is easily accomplished by adding a FileHandler
to your logging
object. Easy peasy.
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
.
Is it possible to do? How?
There seems to be no way to do this through the API.
However, you can do the following:
Looking at the argparse.py source code there doesn't seem to be a way to configure this behaviour.
My suggestion(s) would be:
Override/patch:
print_*
method(s)error
method.The
print_*
method(s) seem to take an optionalfile
argument which defaults to_sys.stdout
.Update: Alternatively you could do something like this whereby you redirect
sys.stdout
temporarily while you parse arguments: