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?

countunique
  • 4,068
  • 6
  • 26
  • 35

2 Answers2

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()
chepner
  • 497,756
  • 71
  • 530
  • 681
countunique
  • 4,068
  • 6
  • 26
  • 35
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:
jayelm
  • 7,236
  • 5
  • 43
  • 61