I would like to add groups in a subparser.
parser = argparse.ArgumentParser(description="A Pipeline.")
subparsers = parser.add_subparsers(
help="Choose imagery source", dest="imagery_source"
)
animal_parser = subparsers.add_parser("animal")
group1_parser = animal_parser.add_argument_group("for_dog_config")
group1_parser.add_argument("--dog", type=str)
group2_parser = animal_parser.add_argument_group("for_cat_config")
group2_parser.add_argument("--cat", type=str)
args = parser.parse_args()
print(args)
run_pipeline animal --dog hello --cat world
Here is the output of namespace.
Namespace(cat='world', dog='hello', imagery_source='animal')
What I would like is that the cat
and dog
are in different namespaces or dictionaries respectively. Is it possible?
Note: I know there are other answers using add_argument_group
in ArgumentParser
object, but I need to use subparsers = prser.add_subparsers
here.
=========== Update ===========
This code block almost do what I need.
def get_arg(parser):
args = parser.parse_args()
args_groups = {}
for group in parser._action_groups:
group_dict = {a.dest: getattr(args, a.dest, None) for a in group._group_actions}
args_groups.update({group.title: argparse.Namespace(**group_dict)})
return args_groups
parser = argparse.ArgumentParser(description="A Pipeline.")
subparsers = parser.add_subparsers(
help="Choose imagery source", dest="imagery_source"
)
group1_parser = parser.add_argument_group("for_dog_config")
group1_parser.add_argument("--dog", type=str)
group2_parser = parser.add_argument_group("for_cat_config")
group2_parser.add_argument("--cat", type=str)
args = get_arg(parser)
print(args)
Execute run_stereo_pipeline --dog hello --cat world
The output is
{'positional arguments': Namespace(imagery_source=None), 'optional arguments': Namespace(help=None), 'for_dog_config': Namespace(dog='hello'), 'for_cat_config': Namespace(cat='world')}
As you can see, now I can do things like args["for_cat_config"]
to get all arguments in the "for_cat_config"
group. But in this approach, I can not specify animal
source which is what I want in the question.