Search code examples
pythonpython-3.xargparse

Custom usage message for many-valued argument


Given sth. like (or similar to):

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("FILES", nargs="+", type=str)
args = parser.parse_args()

Now I'd like to have the many-valued positional argument FILES displayed in the usage message as

usage: cli.py [-h] FILES

instead of

usage: cli.py [-h] FILES [FILES ...]

Any step-by-step explanations or pointers are appreciated.


Solution

  • This is the built-in behavior of the default formatter: source.

    You could have your custom formatter with special handling for the nargs="+" type arguments:

    import argparse
    
    
    class CustomFormatter(argparse.HelpFormatter):
        def _format_args(self, action, default_metavar):
            get_metavar = self._metavar_formatter(action, default_metavar)
            if action.nargs == argparse.ONE_OR_MORE:
                return '%s' % get_metavar(1)
            else:
                return super(CustomFormatter, self)._format_args(action, default_metavar)
    
    
    parser = argparse.ArgumentParser(formatter_class=CustomFormatter)
    parser.add_argument("FILES", nargs="+", type=str)
    args = parser.parse_args()
    

    Would print out:

    usage: cli.py [-h] FILES
    cli.py: error: the following arguments are required: FILES