5

I'm using argparse with optional parameter, but I want to avoid having something like this : script.py -a 1 -b -a 2 Here we have twice the optional parameter 'a', and only the second parameter is returned. I want either to get both values or get an error message. How should I define the argument ?

[Edit] This is the code:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-a', dest='alpha', action='store', nargs='?')
parser.add_argument('-b', dest='beta', action='store', nargs='?')

params, undefParams = self.parser.parse_known_args()
Pendus
  • 51
  • 1
  • 3
  • Show us the code you have so far, otherwise we can and will not help you ... – Bas Swinckels May 10 '15 at 09:42
  • Try https://docs.python.org/3/library/argparse.html#nargs – dav1d May 10 '15 at 09:46
  • 1
    I've added the code. But this link is not helping. I don't want an option to be specified twice. Current this is what is happening : script.py -a 1 -b 2 -a 3 ---> gives a=3 and b=2 without error and no info on the first param. I just want to consider having same optional parameter twice as error. – Pendus May 10 '15 at 10:06
  • Yes, at the very least, issuing a warning would be helpful. Looks like just another argparse deficiency. :-( – GLRoman Oct 29 '19 at 19:30

1 Answers1

7

append action will collect the values from repeated use in a list

parser.add_argument('-a', '--alpha', action='append')

producing an args namespace like:

namespace(alpha=['1','3'], b='4')

After parsing you can check args.alpha, and accept or complain about the number of values. parser.error('repeated -a') can be used to issue an argparse style error message.

You could implement similar functionality in a custom Action class, but that requires understanding the basic structure and operation of such a class. I can't think anything that can be done in an Action that can't just as well be done in the appended list after.

https://stackoverflow.com/a/23032953/901925 is an answer with a no-repeats custom Action.

Why are you using nargs='?' with flagged arguments like this? Without a const parameter this is nearly useless (see the nargs=? section in the docs).

Another similar SO: Python argparse with nargs behaviour incorrect

Community
  • 1
  • 1
hpaulj
  • 221,503
  • 14
  • 230
  • 353