如何通过选择防止多次出现可选参数

问题描述 投票:1回答:1

我正在python 2.7中使用argparse。我想防止用户多次调用my_app.py--cache可选参数。 -cache(或--cache)是带有选项的可选参数,具有const和默认值。代码:

parser = argparse.ArgumentParser()
parser.add_argument("-cache","-- 
cache",required=False,const='all',default=None,nargs='?',choices=["server-only","local-only","all"], 
help="Activate Cache by choosing one of the list choices. e.g. -cache=local-only")

我想在用户以以下形式调用my_app.py时引发异常:

#if he calls with multiple --cache arguments, argparse takes the last dilvered one !! But i want to 
raise an exception here!
my_app.py --cache --cache=server-only

在链接multiple argument occurrence 中的类似问题中没有足够的答案

python argparse
1个回答
2
投票

您可以定义一个自定义操作,该操作在第一次使用该选项时会“记住”,然后在第二次使用该选项时会引发异常。

import argparse


class OneTimeAction(argparse._StoreAction):
    def __init__(self, *args, **kwargs):
        super(OneTimeAction, self).__init__(*args, **kwargs)
        self.seen = False

    def __call__(self, parser, namespace, values, option_string, **kwargs):
        if self.seen:
            parser.error("Cannot use {} a second time".format(option_string))
        super(OneTimeAction, self).__call__(parser, namespace, values, option_string, **kwargs)
        self.seen = True


parser = argparse.ArgumentParser()
parser.add_argument("-cache", "--cache", 
                    action=OneTimeAction,
                    default="all",
                    choices=["server-only", "local-only", "all"],
                    help="Activate Cache by choosing one of the list choices. e.g. -cache=local-only")

[一般来说,您可以将其定义为可与任何类型的操作一起使用的混入。下面的示例还将参数的大部分配置折叠到定制操作本身中。

class OneTimeMixin(object):
    def __init__(self, *args, **kwargs):
        super(OneTimeMixin, self).__init__(*args, **kwargs)
        self.seen = False

    def __call__(self, parser, namespace, values, option_string, **kwargs):
        if self.seen:
            parser.error("Cannot use {} a second time".format(option_string))
        super(OneTimeMixin, self).__call__(parser, namespace, values, option_string, **kwargs)
        self.seen = True


class CacheAction(OneTimeMixin, argparse._StoreAction):
    def __init__(self, *args, **kwargs):
        kwargs.setdefault('choices', ["server-only", "local-only", "all"])
        kwargs.setdefault('default', 'all')
        kwargs.setdefault('help', "Activate Cache by choosing one of the list choices. e.g. -cache=local-only")
        super(CacheAction, self).__init__(*args, **kwargs)


parser = argparse.ArgumentParser()
parser.add_argument("-cache", "--cache", action=CacheAction)
© www.soinside.com 2019 - 2024. All rights reserved.