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()
  • Possible duplicate of [Argparse: Required argument 'y' if 'x' is present](https://stackoverflow.com/questions/19414060/argparse-required-argument-y-if-x-is-present) – Ash Sharma Jun 25 '18 at 09:19

1 Answers1

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)
alec_djinn
  • 10,104
  • 8
  • 46
  • 71