import argparse class ArgumentParser(argparse.ArgumentParser): """ extended with some optparse functionality """ def get_option(self, opt_str): """action with opt_str flag None if no match """ return self._option_string_actions.get(opt_str) def get_action_by_dest(self, dest): """action with matching 'dest' empty list if no match""" return [a for a in self._actions if a.dest==dest] def option_groups(self): """the parser action_groups Argument Groups are different in argparse They are only used for input, and for help display They are not used in parsing Their ._actions list is shared with the parser Their own actions are available in ._group_actions All actions belong to a group. There are 2 default groups to see group titles use [i.title for i in p.option_groups()] """ return self._action_groups[:] def option_list(self): "list of all actions" return self._actions[:] def get_option_group(self, opt_str): """action group that contains this action match on flag or dest an action does not record its 'container' so we have to search the groups Here we accept either flag strings or dest values """ dest = None if opt_str.startswith('-'): dest = self.get_option(opt_str) if dest: dest = dest.dest if dest is None: dest = opt_str for g in self.option_groups(): actions = [a for a in g._group_actions if a.dest==dest] if actions: break return g if actions else None if __name__=='__main__': p = ArgumentParser() g = p.add_argument_group('test group') g.add_argument('foo') p.add_argument('-b','--bar') p.add_argument('duplicate') g.add_argument('-d', dest='duplicate') # duplicate dest p.print_help() print() print('help help:\n', p.get_option('-h').help) print('1st help:\n', p._actions[0].help) print('foo action:\n', p.get_action_by_dest('foo')) print('duplicate actions:\n', p.get_action_by_dest('duplicate')) print('group titles:\n', [g.title for g in p.option_groups()]) print('action dests:\n', [a.dest for a in p.option_list()]) print(p.get_option('--bar').dest, 'is in', p.get_option_group('bar').title) print("bar's group:", p.get_option_group('--bar').title) print("foo's group:",p.get_option_group('foo').title) print("'wrong' not found:", p.get_option_group('wrong')) print('actions by group') # note similarity to parser.format_help # and parser._add_container_actions for g in p.option_groups(): print("\t",g.title) for a in g._group_actions: print("\t\t", a.dest, a.option_strings) # to avoid using private g._group_actions we'd have to add a method # to _ArgumentGroup class