grouping an unknown number of arguments with argparse

ε祈祈猫儿з 提交于 2019-12-04 15:45:14

You can use nargs=4 with an 'append' action:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--group', nargs=4, action='append')

print parser.parse_args()

It'd be called as:

$ python ~/sandbox/test.py --group 1 2 3 4 --group 1 2 3 4
Namespace(group=[['1', '2', '3', '4'], ['1', '2', '3', '4']])

From here, you can parse the key-value pairs if you'd like.


Another option is to use a custom action to do the parsing -- Here's a simple one which accepts arguments of the form --group key:value key2:value2 ... --group ...

import argparse

class DictAction(argparse.Action):
    def __init__(self, *args, **kwargs):
        super(DictAction, self).__init__(*args, **kwargs)
        self.nargs = '*'

    def __call__(self, parser, namespace, values, option_string=None):
        # The default value is often set to `None` rather than an empty list.
        current_arg_vals = getattr(namespace, self.dest, []) or []
        setattr(namespace, self.dest, current_arg_vals)
        arg_vals = getattr(namespace, self.dest)
        arg_vals.append(dict(v.split(':') for v in values))

parser = argparse.ArgumentParser()
parser.add_argument('--group', action=DictAction)

print parser.parse_args()

This has no checking (so the user could get funny TypeErrors if the key:value are not formatted properly) and if you want to restrict it to specified keys, you'll need to build that in as well... but those details should be easy enough to add. You could also require that they provide 4 values using self.nargs = 4 in DictAction.__init__.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!