python argparse extra args

匿名 (未验证) 提交于 2019-12-03 08:33:39

问题:

i would like to get extra args using argparse but without known what are they. for example, in maven we can add parameters in the form: -Dmaven.test.skip=true or -Dcmd=compiler:compile

i would like to get the same thing in python using argparse, and get some kind of dict with all the args..

i know i can use:

aparser.parse_known_args() 

but then i need to parse me extra args (remove the -D and split by =). Was wondering if there is something out of the box?

Thanks!

回答1:

You can use

parser.add_argument('-D', action='append', default=[]) 

which will turn arguments

-Dfoo -Dbar=baz 

into

>>> args.D ['foo', 'bar=baz'] 

And no -D arguments will mean that args.D will return an empty list.


If you want them as a dictionary right there, you can have a custom action:

def ensure_value(namespace, dest, default):     stored = getattr(namespace, dest, None)     if stored is None:         return value     return stored   class store_dict(argparse.Action):     def __call__(self, parser, namespace, values, option_string=None):         vals = dict(ensure_value(namespace, self.dest, {}))         k, _, v = values.partition('=')         vals[k] = v         setattr(namespace, self.dest, vals)   parser.add_argument('-D', default={}, action=store_dict) 

which, given -Dfoo -Dbar=baz will result in

>>> args.D {'bar': 'baz', 'foo': ''} 

which is slightly more verbose than using the action='append' with

>>> as_dict = dict(i.partition('=')[::2] for i in args.D) 


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