解析"python foo.py -DVAR1 = 9 -DVAR2 = Off";与argparse [英] Parsing "python foo.py -DVAR1=9 -DVAR2=Off" with argparse

查看:61
本文介绍了解析"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包中实现了.还有其他类似Python的方法吗?

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 as 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类,该类可以采用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天全站免登陆