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

查看:29
本文介绍了使用 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

为了实现它,我这样做:

To achieve it, I am doing 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天全站免登陆