使用Python argparse的字典 [英] Use dictionary for Python argparse

查看:469
本文介绍了使用Python argparse的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典将人类可读的值映射到三个不同的Python特定值。当用户可以在密钥之间进行选择时,argparse Python模块如何使用这个字典来获取具体的值。



目前我已经有:

  def parse(a):
values = {on:True,off:False,switch:None}
parser = argparse.ArgumentParser()
parser.add_argument( - v,--value,choices = values,default = None)
args = parser.parse_args(a)
print({}:{}。format(type(args.value),args.value))

>>> parse([' - v','on'])
< type'str'> ;: on
>>> parse([' - v','off'])
< type'str'> ;: off
>>> parse([' - v','switch'])
< type'str'> ;: switch
>>> parse([])
< type'NoneType'> ;:无

是,argparse不返回 True False 如果给出参数。有没有简单的方法来添加这个功能?我当然可以这样执行:

  args.value = values [args.value] 

这实际上是我目前正在做的,但是这对默认值不行(我会必须检查该值是否已经为None,或将默认值设置为switch)。而且,在多次使用这个时候,我每次都要这样做。

解决方案

最小的变化是使用

  args.value = values.get(args.values)

所以你不会得到没有任何条目不在dict(例如默认)。



另一个选项是滥用argparse的类型关键字:

  values = {on:True,off:False,switch :$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ 
$ b

类型方法打破了上述使用的选择,因为转换后应用了选择。保留您使用选择的一种可能是:

  def convertvalues(value):
return values.get值,值)
parser.add_argument(' - v',' - value',type = convertvalues,
choices = [True,False,None],
default = b $ b

在这种情况下,如果on,off,switch和none,convertvalues将返回正确的值被使用并返回给定的值,如果有其他的东西(例如'bla')。由于'bla'不在选择中,您会收到预期的错误消息。



使用action与派生自argparse.Action而不是类型的类应该执行该作业在文档中给出的智能方式:

  class DictAction(argparse.Action):
def __call __(self,parser,namespace,values,option_string = None):
value_dict = {on:True,off:False,switch:None}
setattr(namespace,self.dest,value_dict.get(values))
parser.add_argument(' -v',' - value',action = DictAction,
choices = ['on','off','switch'],
default = None)

当然这并不完美,一个更好的解决方案将覆盖Acion init 以获取字典并省略硬编码的value_dict。


I have a dictionary which maps human readable values to three different Python specific values. How can the argparse Python module use this dictionary to get me the specific values while the user can choice between the keys.

Currently I have this:

def parse(a):
    values = { "on": True, "off": False, "switch": None }
    parser = argparse.ArgumentParser()
    parser.add_argument("-v", "--value", choices=values, default=None)
    args = parser.parse_args(a)
    print("{}: {}".format(type(args.value), args.value))

>>> parse(['-v', 'on'])
<type 'str'>: on
>>> parse(['-v', 'off'])
<type 'str'>: off
>>> parse(['-v', 'switch'])
<type 'str'>: switch
>>> parse([])
<type 'NoneType'>: None

The problem is, that argparse doesn't return True, False or None if the parameter is given. Is there an easy way to add this feature? Of course I would be able to execute something like this afterwards:

args.value = values[args.value]

This is actually what I'm doing currently, but this doesn't work well with the default value (I would have to check if the value is already None or set the default to "switch"). And as I'm using this multiple times I would have to do that every time.

解决方案

The smallest change would be to use

args.value = values.get(args.values)

so you would get None for any entry not in the dict (eg default).

Another option is to misuse the type keyword of argparse:

values = { "on": True, "off": False, "switch": None }
def convertvalues(value):
    return values.get(value)
parser.add_argument('-v','--value',type=convertvalues)

The "type" approach breaks the use of choices as used above, since choices is applied after the conversion. One possibility to preserve your use of choices would be:

def convertvalues(value):
     return values.get(value,value)
parser.add_argument('-v','--value',type=convertvalues,
                                   choices=[True,False,None],
                                   default=None)

In this case convertvalues returns the right values if 'on','off','switch' and None are used and returns the given values if something else was given (eg. 'bla'). Since 'bla' is not in choices, you get the expected error message.

Using "action" with a class derived from argparse.Action instead of type should do the job the smart way, as given in the docs:

class DictAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        value_dict = { "on": True, "off": False, "switch": None }
        setattr(namespace, self.dest, value_dict.get(values))
parser.add_argument('-v','--value',action=DictAction,
                                   choices=['on','off','switch'],
                                   default=None)

Of course this is not perfect, a better solution would overwrite the Acion init to get the dictionary and leave out the hardcoded value_dict.

这篇关于使用Python argparse的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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