2
votes

I'm trying to figure out a way to have argparse positional arguments be mutually exclusive to an optional argument.

For example:

./adder 20 32
Output: 52
./adder --interactive
adder>

Right now, if I were to just try '--interactive', it tells me that I'm missing positional arguments.

Example code:

parser = argparse.ArgumentParser()
parser.add_argument('a', metavar='First')
parser.add_argument('b', metavar='Second')
parser.add_argument('--interactive')
parser.parse_args()

I was wondering if there is an elegant way to do this (preferably using argparse functionality) so that '--interactive' disables the requirement of using the two positional arguments.

1
can we see the actual code where you specify the args and such? - gold_cy
Just added example code - user6568026
have you tried add_argument('parms', nargs='*')? arguments are gathered into a list, if positional argument absent, list is empty. - georgexsh
The mutually_exclusive_group mechanism, docs.python.org/3/library/argparse.html#mutual-exclusion, accepts on 'optional' (? or *) positional argument - hpaulj

1 Answers

0
votes

Usually positional arguments can not be omitted. You can try nargs='*' as an alternative.

parser = argparse.ArgumentParser()
parser.add_argument('ab', nargs='*', type='int')
parser.add_argument('--interactive', action='store_true')
args = parser.parse_args()

Use list args.ab to store positional argument. If it is omitted, then args.ab will be an empty list.