Rutsavage
Rutsavage

Reputation: 33

Manual command specification in Python argparse

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?

Upvotes: 3

Views: 89

Answers (1)

ewcz
ewcz

Reputation: 13087

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

Upvotes: 2

Related Questions