Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argparse: Mutually exclusive group with some compatible arguments

I would like to implement logic like this in argparse:

If argument A is selected, the user cannot select arguments B or C.
B and C can both be selected

It looks like add_mutually_exclusive_group is what I would want for this, but it looks like you can only choose one option from a mutually exclusive group, so I cannot put all three in a mutually exclusive group.

Is there a way to do this in argparse?

like image 492
Kevin Burke Avatar asked Dec 17 '12 17:12

Kevin Burke


1 Answers

You could not really do it with argparse, however you can do it after argparse has run.

Here is an example:

parser = argparse.ArgumentParser()

# group 1 
parser.add_argument("-q", "--query", help="query", required=False)
parser.add_argument("-f", "--fields", help="field names", required=False)

# group 2 
parser.add_argument("-a", "--aggregation", help="aggregation",
                    required=False)

I am using here options given to a command line wrapper for querying a mongodb. The collection instance can either call the method aggregate or the method find with to optional arguments query and fields, hence you see why the first two arguments are compatible and the last one isn't.

So now I run parser.parse_args() and check it's content:

args = parser().parse_args()

print args.aggregation
if args.aggregation and (args.query or args.fields):
    print "-a and -q|-f are mutually exclusive ..."
    sys.exit(2)

Of course, this little hack is only working for simple cases and it would become a nightmare to check all the possible options if you have many mutually exclusive options and groups. In that case you should break your options in to command groups. For that, you should follow the suggestion here Python argparse mutual exclusive group.

like image 116
oz123 Avatar answered Oct 03 '22 23:10

oz123