Home Blog CV Projects Patterns Notes Book Colophon Search

Grouping args by their argparse group

8 Feb, 2023

From https://stackoverflow.com/questions/38884513/python-argparse-how-can-i-get-namespace-objects-for-argument-groups-separately

import argparse
parser = argparse.ArgumentParser()

group1 = parser.add_argument_group('group1')
group1.add_argument('--test1', help="test1")

group2 = parser.add_argument_group('group2')
group2.add_argument('--test2', help="test2")

args = parser.parse_args()

arg_groups={}

for group in parser._action_groups:
    group_dict={action.dest:getattr(args,action.dest,None) for action in group._group_actions}
    arg_groups[group.title]=argparse.Namespace(**group_dict)

print(arg_groups)

Comments

Be the first to comment.

Add Comment





Copyright James Gardner 1996-2020 All Rights Reserved. Admin.