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

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

问题描述

我有一个字典,它将人类可读的值映射到三个不同的 Python 特定值.argparse Python 模块如何使用此字典来获取特定值,同时用户可以在键之间进行选择.

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.

目前我有这个:

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

问题是,如果给定参数,argparse 不会返回 TrueFalseNone.有没有简单的方法来添加这个功能?当然,我可以在之后执行这样的操作:

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]

这实际上是我目前正在做的事情,但这不适用于默认值(我必须检查该值是否已经为 None 或将默认值设置为 "switch").由于我多次使用它,因此每次都必须这样做.

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.

推荐答案

最小的变化是使用

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

因此对于不在字典中的任何条目(例如默认值),您将获得 None .

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

另一种选择是滥用argparse的type关键字:

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)

在这种情况下,如果使用了 'on'、'off'、'switch' 和 None,则 convertvalues 返回正确的值,如果给出了其他内容(例如,'bla'),则返回给定的值.由于bla"不在选项中,您会收到预期的错误消息.

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.

使用从 argparse.Action 派生的类的action"而不是 type 应该以聪明的方式完成工作,如 文档:

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)

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

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天全站免登陆