解析“python foo.py -DVAR1=9 -DVAR2=Off"使用 argparse [英] Parsing "python foo.py -DVAR1=9 -DVAR2=Off" with argparse

查看:25
本文介绍了解析“python foo.py -DVAR1=9 -DVAR2=Off"使用 argparse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看这个答案,我可以这样做:

parser=argparse.ArgumentParser()
parser.add_argument('-D',action='append',help='FOO=BAR')
options = parser.parse_args('-DVAR1=9 -DVAR2=Off'.split())

我得到:

Namespace(D=['VAR1=9', 'VAR2=Off'])

那么说:

[o.split('=') for o in options.D]

结果:

[['VAR1', '9'], ['VAR2', 'Off']]

这基本上就是我需要的,但我觉得这是一个常见的操作,可能已经在 ArgParse 包中实现了.有没有更Pythonesque的方式来做到这一点?

This is basically what I need, but I feel this is a common action that might already have an implementation within the ArgParse package. Is there a more Pythonesque way of doing this?

推荐答案

我认为 argparse 开发人员(和其他 POSIX 样式解析器)希望您定义 --dvar1--dvar2 参数,而不是这种开放式方法.

I think the argparse developers (and other POSIX style parsers) expect you to define --dvar1 and --dvar2 arguments, rather than this open ended approach.

其他人询问了某种一般的key=value 输入.argparse 中没有任何东西可以直接处理它.所以像你一样收集字符串并在解析后拆分它们看起来很好.你所做的和我所见过的一样干净和清晰.

Others have asked about some sort of general key=value input. There's nothing in argparse that handles that directly. So collecting the strings as you do and splitting them after parsing looks fine. What you are doing is as clean and clear as anything I've seen.

您可以使用 type 函数即时进行拆分:

You could do that splitting on-the-fly with a type function:

In [38]: import argparse
In [39]: def foo(astr):
    ...:     return astr.split('=')
    ...: 
In [40]: parser=argparse.ArgumentParser()
In [41]: parser.add_argument('-D',action='append',type=foo)
Out[41]: _AppendAction(option_strings=['-D'], dest='D', nargs=None, const=None, default=None, type=<function foo at 0xab0c765c>, choices=None, help=None, metavar=None)
In [42]: options = parser.parse_args('-DVAR1=9 -DVAR2=Off'.split())
In [43]: options
Out[43]: Namespace(D=[['VAR1', '9'], ['VAR2', 'Off']])

python argparse 存储 --foo=bar 作为 args.key='foo', args.value='bar'

采用不同的方法 - 子类化 Action.如果您愿意,那将是必需的

takes a different approach - subclassing Action. That would be needed if you wanted

namespace(VAR1='9', VAR2='Off')

(您的后处理循环可以将类似的属性写入 namespace.另一种自定义技巧是定义一个自定义的 Namespace 类,该类可以采用 Namespacecode>VAR1=9 字符串并根据需要将其拆分.

(your post processing loop could have written attributes like that to the namespace. Yet another customization trick is to define a custom Namespace class, one that can take the VAR1=9 string and split it as needed.

这篇关于解析“python foo.py -DVAR1=9 -DVAR2=Off"使用 argparse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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