python argparse 额外的参数 [英] python argparse extra args

查看:48
本文介绍了python argparse 额外的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 argparse 获得额外的参数,但不知道它们是什么.例如,在 maven 中,我们可以在表单中添加参数:-Dmaven.test.skip=true-Dcmd=compiler:compile

我想在 python 中使用 argparse 得到同样的东西,并用所有的 args 得到某种 dict ..

我知道我可以使用:

aparser.parse_known_args()

但是我需要解析我额外的参数(删除 -D 并由 = 拆分).想知道是否有开箱即用的东西?

谢谢!

解决方案

可以使用

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

这将变成争论

-Dfoo -Dbar=baz

进入

<预><代码>>>>参数['foo', 'bar=baz']

并且没有 -D 参数意味着 args.D 将返回一个空列表.

<小时>

如果您希望它们就在那里作为字典,您可以有一个自定义操作:

def ensure_value(namespace, dest, default):存储 = getattr(命名空间,目标,无)如果存储为无:返回值返回存储类 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] = vsetattr(命名空间,self.dest,vals)parser.add_argument('-D', default={}, action=store_dict)

其中,给定 -Dfoo -Dbar=baz 将导致

<预><代码>>>>参数{'bar': 'baz', 'foo': ''}

这比使用 action='append'

稍微冗长<预><代码>>>>as_dict = dict(i.partition('=')[::2] for i in args.D)

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!

解决方案

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)

这篇关于python argparse 额外的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆