Need some help with argparse

Ben Finney ben+python at benfinney.id.au
Tue Oct 3 16:01:22 EDT 2017


Kryptxy via Python-list <python-list at python.org> writes:

> I have a group of arguments, say: (-a, -b, -c, -d, -e) [lets call it group1]
> I have another group, say: (-z, -y, -x, -w) [lets call it group2]

Argument groups are a feature to control the help output from the
parser:

     When an argument is added to the group, the parser treats it just
     like a normal argument, but displays the argument in a separate
     group for help messages.

     <URL:https://docs.python.org/3/library/argparse.html#argument-groups>

> Now I want to get arguments of group1 and group2 separately.

You don't want to use the “argument groups” feature for that, because
that's not what it does.

> How can I get all arguments of group 1 ONLY? Same goes for group 2?
> I tried subparsers too - but they require a mandatory `positional
> argument` - which is not application's requirement.

I don't know of a way to have the argument parser know the separation
you're talking about, without using a subparser.

You will need to maintain that separation yourself, outside the parser.

One simple way (I have not tried this)::

    argument_names_by_group = {
            'foo': {'lorem', 'donec', 'fusce'},
            'bar': {'aliquam', 'nunc'},
    }

    args = parser.parse_args()

    args_by_group = {
            group_name: {
                getattr(arg_name)
                for arg_name in argument_names_by_group[group_name]
            }
            for group_name in argument_names_by_group
    }

-- 
 \             “I believe our future depends powerfully on how well we |
  `\     understand this cosmos, in which we float like a mote of dust |
_o__)                 in the morning sky.” —Carl Sagan, _Cosmos_, 1980 |
Ben Finney




More information about the Python-list mailing list