Python argparse : How can I make an argument and a group of argument mutually exclusive?

Viewed 31

I have 4 different arguments, let's call them A, B, C and D

I would like A to be exclusive from B, C and D but B, C and D should always be called together

In the argparse documentation I found the add_mutually_exclusive_group method but it would make my arguments A, B, C and D all exclusive from one another

How can I require my argument to by either [A] or [B and C and D] ?

1 Answers

Since it seems like I cannot use argparse directly with the configuration I wanted to get, here is how I proceeded with Python :

import argparse
import sys

parser = argparse.ArgumentParser(description="Test program")
parser.add_argument('-a', type=str, help="arg A")
parser.add_argument('-b', type=str, help="arg B")
parser.add_argument('-c', type=str, help="arg C")
parser.add_argument('-d', type=str, help="arg D")
args = parser.parse_args(sys.argv[1:])

if args.a is None and args.b is None and args.c is None and args.d is None:
    print("Error : at least one argument is required")
    exit(1)
if args.a:
    if args.b or args.c or args.d:
        print("Error argument a cannot be used with arguments b, c and d")
        exit(1)
    print("scenario with argument a")
else:
    if args.b is None or args.c is None or args.d is None:
        print("when not using argument a, arguments b, c and d must all be set")
        exit(1)
    print("scenario with arguments b, c and d")

This covers all of the mentioned use cases

Related