6

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()
4
  • Show us the code you have so far, otherwise we can and will not help you ... Commented May 10, 2015 at 9:42
  • Try docs.python.org/3/library/argparse.html#nargs Commented May 10, 2015 at 9: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. Commented May 10, 2015 at 10:06
  • Yes, at the very least, issuing a warning would be helpful. Looks like just another argparse deficiency. :-( Commented Oct 29, 2019 at 19:30

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.