2

I would like a behavior where exactly one of

  • --a
  • --b AND --c

are required. I know how to do it if the second requirement were just --b:

group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--a', type=str)
group.add_argument('--b', type=str)
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
extremeaxe5
  • 723
  • 3
  • 13
  • Does this answer your question? [Python argparse mutual exclusive group](https://stackoverflow.com/questions/17909294/python-argparse-mutual-exclusive-group) – Yevhen Kuzmovych May 31 '23 at 14:50
  • Are you trying to make is so if `--b` is passed, then `--c` is required as well? Or that the user can pass `--a` or either of `--b` or `--c`? – James May 31 '23 at 14:51
  • no nesting of groups like this. – hpaulj May 31 '23 at 15:39

1 Answers1

1

Here is how I would do it:

parser = argparse.ArgumentParser()

# group 1 
parser.add_argument("--a", type=str)

# group 2 
parser.add_argument("--b", type=str)
parser.add_argument("--c", type=str)

args = parser.parse_args()

if args.a and (args.b or args.c):
    print("-a and -b|-c are mutually exclusive ...")
    sys.exit(2)
Jose
  • 632
  • 1
  • 13