I need to parse additional arguments depending on the value of a conditional argument ('--name'). I don't want to handle it with 'if statements'.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--name", required = True, choices = ['a','b','c'])
args = parser.parse_args()
if args.name== 'a':
parser.add_argument( add some mandatory arguments here )
if args.name== 'b':
parser.add_argument( add some mandatory arguments here )
if args.name== 'c':
parser.add_argument( add some mandatory arguments here )
args = parser.parse_args()
I got a similar question on this Python argparse conditional arguments but the solution doesn't help me.
Note: I'm using python 2.7
subparsersis the the mechanism thatargparseprovides for this - butnamehas to be a positional argument, not a flagged one.parse_known_argsto read--name. That way it won't complain about the additional strings. But a good alternative to conditionaladd_argumentis to accept all of the possible flagged arguments, and then test for required values after parsing. And with good choices of defaults, you might not even need to require certain arguments.add_subparsersthat creates a flagged (optionals) argument rather than the normal positional. That is, one that accepts '--name a' instead of 'a'. But it's not thoroughly tested, and not something that I've seen anyone else propose on SO.