【发布时间】:2020-04-30 20:51:12
【问题描述】:
我在 python 2.7 中使用 argparse。我想阻止用户多次调用 my_app.py --cache 可选参数。 -cache(或--cache)是带有选项的可选参数,有一个常量和一个默认值。代码:
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 中的类似问题没有足够的答案
【问题讨论】:
-
一种解决方案是将选项值保存在列表中。然后,在解析选项后,检查列表长度并给出错误是 2 或更多。使用
action="append"和default=[]收集列表中的选项值。 -
@TomKarzes - 很棒且快速的答案。在我发布我的问题之前,我已经尝试过完全了解这个概念(同样的想法),并且我已经将默认值更改为保存一个列表,但我唯一错过的是 action="apend"!谢谢。
-
默认的
argparse行为是将default放在命名空间中,然后允许每个实例覆盖它,实际上以最后一个用户提供的值(如果有)结束。为什么要这么拼?您的用户是否特别喜欢出于某种特殊目的使用--cache --cache=foobar?