2
parser = argparse.ArgumentParser()
parser.add_argument("first_arg")
parser.add_argument("--second_arg")

I want to say that second_arg should only be accepted when first_arg takes a certain value , for example "A". How can I do this?

2 Answers 2

1
import argparse

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()

parser_a = subparsers.add_parser('firstvalue')
parser_a.add_argument('bar', choices='A')
parser_a.add_argument("--second_arg")

args = parser.parse_args()
Sign up to request clarification or add additional context in comments.

Comments

0

It may be simplest just to do this manually after parsing args:

import sys
args = parser.parse_args()
if args.first_arg != 'A' and args.second_arg: # second_arg 'store_true'
    sys.exit("script.py: error: some error message")

Or if second_arg isn't store_true, set second_arg's default to None. Then the conditional is:

if args.first_arg != 'A' and args.second_arg is not None:

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.