python - argparse -- requiring either 2 values or none for an optional argument -
i'm trying make optional argument script can either take no values or 2 values, nothing else. can accomplish 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 action") args = parser.parse_args() # output: # ./script.py -a --> works # ./script.py -a val1 --> works # ./script.py -a val1 val2 --> error
version 2 - accepts 2 values:
parser = argparse.argumentparser() parser.add_argument("-a", "--action", nargs=2, action="store", help="do action") args = parser.parse_args() # output: # ./script.py -a --> error # ./script.py -a val1 --> error # ./script.py -a val1 val2 --> works
how combine these 2 different versions script accepts 0 or 2 values argument, rejects when has 1 value?
you'll have own error checking here. accept 0 or more value, , reject other 0 or 2:
parser = argparse.argumentparser() parser.add_argument("-a", "--action", nargs='*', action="store", help="do action") args = parser.parse_args() if args.action not none , len(args.action) not in (0, 2): parser.error('either give no values action, or two, not {}.'.format(len(args.action)))
note args.action
set none
when no -a
switch used:
>>> import argparse >>> parser = argparse.argumentparser() >>> parser.add_argument("-a", "--action", nargs='*', action="store", help="do action") _storeaction(option_strings=['-a', '--action'], dest='action', nargs='*', const=none, default=none, type=none, choices=none, help='do action', metavar=none) >>> args = parser.parse_args([]) >>> args.action none true >>> args = parser.parse_args(['-a']) >>> args.action []
Comments
Post a Comment