蟒蛇argparse附加参数 [英] python argparse extra args
问题描述
我想通过获得额外的参数 argparse
但不知道他们是什么。
例如,行家
我们就可以在表单中添加参数: -Dmaven.test.skip = TRUE
或 -Dcmd =编译:编译
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
我想用得到的蟒蛇一样的东西 argparse
,并得到某种字典
与所有在ARGS ..
i would like to get the same thing in python using argparse
, and get some kind of dict
with all the args..
我知道我可以使用:
aparser.parse_known_args()
但后来我需要解析我额外的参数(由 =
删除 -D
和分裂)。想知道如果有一些现成的?
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?
谢谢!
推荐答案
您可以使用
parser.add_argument('-D', action='append', default=[])
这将打开参数
-Dfoo -Dbar=baz
到
>>> args.D
['foo', 'bar=baz']
和没有 -D
参数将意味着 args.D
将返回一个空列表。
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)
其中,由于 -Dfoo -Dbar =巴兹
将导致
>>> args.D
{'bar': 'baz', 'foo': ''}
这是略的比使用行动='追加'更详细
与
>>> as_dict = dict(i.partition('=')[::2] for i in args.D)
这篇关于蟒蛇argparse附加参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!