11

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?

1

2 Answers 2

7

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')
Sign up to request clarification or add additional context in comments.

Comments

0

You can do something similar to this using sub_parsers.

Here are the docs and examples:

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

1 Comment

Unfortunately, this wouldn't work, because arg1 needs to be dynamic. Sub-commands are fixed strings. For example, prog multiarg arg1 arg2, where multiarg is the fixed command string. Also, even after adding a sub-command you would end up with the same situation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.