While Jonathan's answer is great for complex options, there is a very simple solution that will work for simple cases, for example. 1 excludes 2 other options, such as
command [- a xxx | [ -b yyy | -c zzz ]]
or even as in the original question:
pro [-a xxx | [-b yyy -c zzz]]
Here's how I do it:
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 the options provided by the shell for requesting mongodb. The collection instance can either call the aggregate method or the find method with additional query and fields arguments, so you can see why the first two arguments are compatible and the last is not.
So now I run parser.parse_args() and check its contents:
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 works only for simple cases, and for nightmares one could check all possible options if you have many mutually exclusive options and groups. In this case, you must break down your options in team groups, as Jonathan suggested.
Oz123 Dec 28 '14 at 10:38 2014-12-28 10:38
source share