Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating mutually inclusive positional arguments with argparse

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?

like image 860
Michael Mulich Avatar asked Apr 10 '13 19:04

Michael Mulich


People also ask

How do you make an argument optional in Argparse?

Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser.

What does Argparse ArgumentParser ()?

The ArgumentParser.parse_args() method runs the parser and places the extracted data in a argparse.Namespace object: args = parser. parse_args() print(args.

What is a Subparser?

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.


1 Answers

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')
like image 127
mx0 Avatar answered Nov 09 '22 16:11

mx0