I'm trying to build a command line interface with Python's argparse module. I want two positional arguments where one depends on the other (mutually inclusive). Here is what I want:
prog [arg1 [arg2]]
Here's what I have so far:
prog [arg1] [arg2]
Which is produced by:
parser = argparse.ArgumentParser()
parser.add_argument('arg1', nargs='?')
parser.add_argument('arg2', nargs='?')
How do I get from there to having a mutually inclusive arg2?
Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser.
The ArgumentParser.parse_args() method runs the parser and places the extracted data in a argparse.Namespace object: args = parser. parse_args() print(args.
A “subparser” is an argument parser bound to a namespace. In other words, it works with everything after a certain positional argument. Argh implements commands by creating a subparser for every function.
Module argparse
doesn't have options for creating mutually inclusive arguments.
However it's simple to write it by yourself.
Start with adding both arguments as optional:
parser.add_argument('arg1', nargs='?')
parser.add_argument('arg2', nargs='?')
After parsing arguments check if arg1
is set and arg2
is not:
args = parser.parse_args()
if args.arg1 and not args.arg2:
(this may be more tricky if you change default value from None
for not used arguments to something different)
Then use parser.error()
function to display normal argparse
error message:
parser.error('the following arguments are required: arg2')
Finally change usage: message to show that arg2
depends on arg1
:
parser = argparse.ArgumentParser(usage='%(prog)s [arg1 [arg2]]')
A complete script:
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With