Creating mutually-inclusive positional arguments with argparse

I am trying to create a command line interface with the pparon argparse module. I want two positional arguments, where one depends on the other (mutually inclusive). Here is what I want:

prog [arg1 [arg2]] 

Here is what I still have:

 prog [arg1] [arg2] 

What is produced:

 parser = argparse.ArgumentParser() parser.add_argument('arg1', nargs='?') parser.add_argument('arg2', nargs='?') 

How do I get from there to have mutually included arg2?

+5
source share
2 answers

You can do something like this using sub_parsers .

Here are the docs and examples:

http://docs.python.org/2/library/argparse.html#sub-commands

0
source

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') 
0
source

All Articles