问题
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)
来源:https://stackoverflow.com/questions/29335145/python-argparse-extra-args