Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argparse : how to detect duplicated optional argument?

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()
like image 579
Pendus Avatar asked May 10 '15 09:05

Pendus


1 Answers

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

like image 111
hpaulj Avatar answered Oct 16 '22 17:10

hpaulj