I'm trying to make an optional argument for a script that can either take no values or 2 values, nothing else. Can you accomplish this using argparse?
# desired output:
# ./script.py -a --> works
# ./script.py -a val1 --> error
# ./script.py -a val1 val2 --> works
version 1 -- accepts 0 or 1 values:
parser = argparse.ArgumentParser()
parser.add_argument("-a", "--action", nargs="?", const=True, action="store", help="do some action")
args = parser.parse_args()
# output:
# ./script.py -a --> works
# ./script.py -a val1 --> works
# ./script.py -a val1 val2 --> error
version 2 - accepts exactly 2 values:
parser = argparse.ArgumentParser()
parser.add_argument("-a", "--action", nargs=2, action="store", help="do some action")
args = parser.parse_args()
# output:
# ./script.py -a --> error
# ./script.py -a val1 --> error
# ./script.py -a val1 val2 --> works
How do you combine these 2 different versions so that the script accepts 0 or 2 values for the argument, but rejects it when it only has 1 value?
Just handle that case yourself:
Of course you should update the help text in that case so that the user has a chance to know this before running into the error.
You'll have to do your own error checking here. Accept 0 or more value, and reject anything other than 0 or 2:
Note that
args.action
is set toNone
when no-a
switch was used:Have your option take a single, optional comma-separated string. You'll use a custom type to convert that string to a list and verify that it has exactly two items.
Then you'd use it like
You can adjust the definition of
pair
to use a different separator and to return something other than a list (a tuple, for example).The
metavar
provides a better indication that the argument toaction
is a pair of values, rather than just one.How about the required argument:
parser.add_argument("-a", "--action", nargs=2, action="store", help="do some action", required=False)