0

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

3
  • subparsers is the the mechanism that argparse provides for this - but name has to be a positional argument, not a flagged one. Commented Oct 17, 2018 at 16:12
  • In your sketched code, use parse_known_args to read --name. That way it won't complain about the additional strings. But a good alternative to conditional add_argument is 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. Commented Oct 17, 2018 at 16:19
  • I have tested a variation on add_subparsers that 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. Commented Oct 17, 2018 at 19:54

0

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.