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.