0

I have 3 arguments in and mutually exclusive group. I want to make a new mandatory sub-command available for the '-a' argument and this argument should only be available for the '-a' argument.

What is the best way to do this? I have tried searching and reading this argparse docs But havent figured it out yet.

parser = argparse.ArgumentParser(prog='med-tool test', description='med-tool')
group = parser.add_mutually_exclusive_group(required=True)

parser.add_argument('-f', '--foo')
group.add_argument('-a', '--add', help ="Add device", metavar='')
group.add_argument('-d', '--get', help ="Get device", metavar='')
group.add_argument('-r', '--get', help ="Read device", metavar='')

args = parser.parse_args()
1

1 Answer 1

2

Just add required=True in group.add_argument().

group.add_argument('-a', '--add', help ="Add device", metavar='', required=True)

It is described in the docs you linked, paragraph 15.4.3. The add_argument() method and here.

I am not sure this is really what you want though because it doesn't make sense to add a required argument in a mutually exclusive group. You probably want to modify it into:

parser.add_argument('-a', '--add', help ="Add device", metavar='', required=True)
Sign up to request clarification or add additional context in comments.

3 Comments

I want to make a new sub-command (argument) available to the '-a' argument. So i guess it should be outside the MEG? Like etc: script.py - a test -new house
Yes, put it outside the MEG.
Well that was pretty simple ;) Thanks i have it working now.

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.