使用argparse来解析形式为“arg = val”的参数。 [英] Using argparse to parse arguments of form "arg= val"

查看:217
本文介绍了使用argparse来解析形式为“arg = val”的参数。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用argparse解析arg = val形式的命令行
例如,用法是:

I want to use argparse to parse command lines of form "arg=val" For example, the usage would be:

script.py conf_dir=/tmp/good_conf

this:

desc   = "details"
parser = argparse.ArgumentParser(description=desc, add_help=False)
args = parser.add_argument("conf_dir")
args = parser.parse_args("conf_dir=FOO".split())
args = parser.parse_args()
print args.conf_dir

但是,问题是,在调用脚本时:

But, the problem is that, on invocation of the script with:

python script.py conf_dir=/tmp/good_conf

我得到:

conf_dir=/tmp/good_conf

我预期的地方

/tmp/good_conf

所以,问题是:我可以使用argparse解析cmd行,对?
任何提示?

So, the question is: Can I use argparse to parse cmd line, which contains name value pairs? Any hints?

编辑:我想这样做,而不是像-conf_dir = / tmp / good_dir这样的原因是因为还有其他工具(以其他语言编写),它使用conf_dir = / tmp / good_dir参数样式。为了保持一致性,我以这种方式解析args。

The reason I want to do this and not some thing like --conf_dir=/tmp/good_dir is because there are other tools (written in other language), which uses conf_dir=/tmp/good_dir style of arguments. To maintain consistency, I was to parse args in this way.

推荐答案

根据文档 argparse 本身不允许你有像这样的无前缀的选项。如果省略前导 - ,它假定您描述的是一个位置参数,并希望它被提供为:

As per the documentation, argparse doesn't natively let you have unprefixed options like that. If you omit the leading -, it assumes you are describing a positional argument and expects it to be provided as:

python script.py /tmp/good_conf

它是可选的,它需要被正确标记为一个标志,通过调用 - conf_dir ,并调用如下脚本:

If you want it to be optional, it needs to be correctly marked as a flag by calling it --conf_dir, and invoking the script like:

python script.py --conf_dir=/tmp/good_conf

但是,要接受名称/值对,您可以实施自定义操作。结合 nargs ,这样的操作可以接受任意数量的名称 - 值对,并将它们存储在参数解析结果对象上。

However, to accept name-value pairs, you can implement a custom action. In combination with nargs, such an action could accept an arbitrary number of name-value pairs and store them on the argument parsing result object.

这篇关于使用argparse来解析形式为“arg = val”的参数。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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