Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add optional or once arguments?

How can I add an argument that is optional and must not be specified multiple times?

Valid:

$ ./my.py
$ ./my.py --arg MyArgValue

Invalid:

$ ./my.py --arg MyArgValue --arg ThisIsNotValid

If I add an argument like:

parser.add_argument('--arg', type=str)

The invalid example results in a string ThisIsNotValid. I would expect a parser error.

like image 882
Alex Avatar asked Aug 31 '13 04:08

Alex


People also ask

How do you indicate optional arguments?

To indicate optional arguments, Square brackets are commonly used, and can also be used to group parameters that must be specified together. To indicate required arguments, Angled brackets are commonly used, following the same grouping conventions as square brackets.

How do you make ARG optional?

You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function.

How do you add an optional argument in Argparse?

To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

What are optional arguments in Excel?

Note most arguments are required, but some are optional. In Excel, optional arguments are denoted with square brackets. For example, the fourth argument in VLOOKUP function, range_lookup, is optional and appears in square brackets as shown above.


1 Answers

Create a custom action that raises an exception if the same argument is seen twice. When the parser catches the exception, it prints the usage and a nicely-formatted error message.

import argparse

class Highlander(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        if getattr(namespace, self.dest, None) is not None:
            raise argparse.ArgumentError(self, 'There can be only one.')
        setattr(namespace, self.dest, values)

parser = argparse.ArgumentParser()
parser.add_argument('-f', action=Highlander)
print (parser.parse_args('-f 1 -f 2'.split()))
like image 120
Robᵩ Avatar answered Oct 07 '22 20:10

Robᵩ