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.
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.
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.
To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
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.
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()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With