Argparse:如何使用 nargs='*' 来创建 const 的等价物

问题描述 投票:0回答:2

有没有一种方法可以生成

const
的等价物(我们可以与
nargs='?'
一起使用,请参阅此处 参考问题 作为示例),但是对于
nargs='*'
。这意味着我想要:

import argparse

argparser = argparse.ArgumentParser()
argparser.add_argument('--option', nargs='*', const=[1, 2, 3])
print(argparser.parse_args())

然后在使用过程中:

my_script.py               #  Namespace(option=None)
my_script.py --option      #  Namespace(option=[1, 2, 3])
my_script.py --option 4 5  #  Namespace(option=[4, 5])

目前我得到

ValueError: nargs must be '?' to supply const

python argparse
2个回答
1
投票

您可以使用自定义

action
来实现此结果:

import argparse

p = argparse.ArgumentParser()

class customAction(argparse.Action):
    """
    Customized argparse action, will set the
    value in the following way:

        1) If no option_string is supplied: set to None

        2) If option_string is supplied:

            2A) If values are supplied:
                set to list of values

            2B) If no values are supplied:
                set to default value (`self.const`)

    NOTES:
        If `const` is not set, default value (2A) will be None
    """
    def __call__(self, parser, namespace, values, option_string=None):
        if option_string:
            setattr(namespace, self.dest, self.const)
        elif not values:
            setattr(namespace, self.dest, None)
        else:
            setattr(namespace, self.dest, values)


p.add_argument('--option',
    nargs='*',
    action=customAction,
    dest='option',
    type=int,
    const=[1, 2, 3]
)

0
投票

对@YaakovBressler 评论的未经测试的更正:

class ConstWithMultiArgs (argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        obj = values if values else self.const if option_string else self.default
        setattr(namespace, self.dest, obj)
© www.soinside.com 2019 - 2024. All rights reserved.