The argparse module has no options for creating mutually inclusive arguments. However, it is easy to write on your own.
Start by adding both arguments as optional:
parser.add_argument('arg1', nargs='?') parser.add_argument('arg2', nargs='?')
After parsing the arguments, check if arg1 installed and not arg2 :
args = parser.parse_args() if args.arg1 and not args.arg2:
(this can be trickier if you change the default value from None for unused arguments to something else)
Then use parser.error() to display the usual argparse error argparse :
parser.error('the following arguments are required: arg2')
Finally, change the use: message to show that arg2 depends on arg1 :
parser = argparse.ArgumentParser(usage='%(prog)s [arg1 [arg2]]')
Full scenario:
import argparse parser = argparse.ArgumentParser(usage='%(prog)s [arg1 [arg2]]') parser.add_argument('arg1', nargs='?') parser.add_argument('arg2', nargs='?') args = parser.parse_args() if args.arg1 and not args.arg2: parser.error('the following arguments are required: arg2')
source share