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
  • 3,790
  • 6
  • 24
  • 32

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
  • 446,329
  • 63
  • 468
  • 610
countunique
  • 3,790
  • 6
  • 24
  • 32
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
  • 6,518
  • 4
  • 40
  • 59