1

I need to have two mutually exclusive groups of arguments in python using ArgumentParser. I use approach suggested by Jonathan here:

subparsers = parser.add_subparsers(help = "You should explicitly specify either group_1 or gropup_2")
    parser_g1 = subparsers.add_parser("group_1")
    parser_g1.add_argument("group_1_arg1")

    parser_g2 = subparsers.add_parser("group_2")
    parser_g2.add_argument("group_2_arg1")
    parser_g2.add_argument("group_2_arg2")

It looks as correct approach, but the problem is to determinate which group was choosen in runtime. If first argument was group_1 I get exception assigning args.group_2_arg1 and args.group_2_arg2. If first argument was group_2 I get exception assigning args.group_1_arg1

The exception is of kind 'Namespace' object has no attribute 'group_1_arg1' Is there any way to check which paser group was used, other, then inspecting Namespace? s

BaruchLi
  • 1,021
  • 2
  • 11
  • 18
  • If you give `add_subparsers` a `dest` parameter, then that will be set to either `group_1` or `group_2`. – hpaulj Jun 10 '20 at 07:29

2 Answers2

1

Well, trivial answer is to use

if hasattr(args, 'group_1_arg1'):

and so for other arguments.

BaruchLi
  • 1,021
  • 2
  • 11
  • 18
1

As you noted, you can use hasattar. But, if there are a lot of arguments and combinations of arguments, you can use the set_defaults functionality of the sub-parsers (note the starred code):

import argparse

parser = argparse.ArgumentParser()

subparsers = parser.add_subparsers(help = "You should explicitly specify either group_1 or gropup_2")
parser_g1 = subparsers.add_parser("group_1")
parser_g1.add_argument("group_1_arg1")
parser_g1.set_defaults(group=1)          # ***

parser_g2 = subparsers.add_parser("group_2")
parser_g2.add_argument("group_2_arg1")
parser_g2.set_defaults(group=2)          # *** 

args = parser.parse_args()
print(args)

When running this script:

./my_script.py group_1 group_1_arg1

The result is:

Namespace(group=1, group_1_arg1='group_1_arg1')
          =======

As you can see, each group will have its own indicator that the group was used.

Roy2012
  • 11,755
  • 2
  • 22
  • 35