3

An example would be better, consider this silly one:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-f', '--foo', nargs='+', help='Spam egg')

parser.parse_args()

When I run the ---help:

usage: foos.py [-h] [-f FOO [FOO ...]]

optional arguments:
  -h, --help            show this help message and exit
  -f FOO [FOO ...], --foo FOO [FOO ...]
                        Spam egg

As i have used nargs ='+', i am getting -f FOO [FOO ...] and similarly -foo FOO [FOO ...], but i want just one FOO to be shown in the --help i.e. i want:

usage: foos.py [-h] [-f FOO]

optional arguments:
  -h, --help            show this help message and exit
  -f FOO, --foo FOO
                        Spam egg

I have taken a look at the argparse doc but could not find anything similar. How can i do this?

2
  • Well, FOO [FOO ...] is just the syntax for at least one, but possibly more, arguments. Commented Feb 9, 2018 at 11:48
  • @Graipher Yes, as I have used nargs='+', but can I drop that reference from help? Commented Feb 9, 2018 at 11:49

1 Answer 1

2

you could implement your own formatter:

import argparse

class MyFormatter(argparse.HelpFormatter):

    def _format_args(self, action, default_metavar):
        get_metavar = self._metavar_formatter(action, default_metavar)
        if action.nargs is None:
            result = '%s' % get_metavar(1)
        elif action.nargs == argparse.OPTIONAL:
            result = '[%s]' % get_metavar(1)
        elif action.nargs == argparse.ZERO_OR_MORE:
            result = '[%s [%s ...]]' % get_metavar(2)

        #let's customize this part
        elif action.nargs == argparse.ONE_OR_MORE:
            #result = '%s [%s ...]' % get_metavar(2)
            result = '%s' % get_metavar(1)

        elif action.nargs == argparse.REMAINDER:
            result = '...'
        elif action.nargs == argparse.PARSER:
            result = '%s ...' % get_metavar(1)
        else:
            formats = ['%s' for _ in range(action.nargs)]
            result = ' '.join(formats) % get_metavar(action.nargs)
        return result

parser = argparse.ArgumentParser(formatter_class = MyFormatter)

parser.add_argument('-f', '--foo', nargs='+', help='Spam egg')
parser.parse_args()

this would give:

usage: test.py [-h] [-f FOO]

optional arguments:
  -h, --help         show this help message and exit
  -f FOO, --foo FOO  Spam egg
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.