argparse - 禁用相同的参数出现 [英] argparse - disable same argument occurrences
问题描述
我正在尝试使用 argparse 在一个命令行中禁用相同的参数出现
I'm trying to disable same argument occurences within one command line, using argparse
./python3 --argument1=something --argument2 --argument1=something_else
这意味着这应该引发错误,因为argument1的值被覆盖,默认情况下,argparse只会覆盖该值并继续像什么也没发生一样......有没有什么聪明的方法可以禁用这种行为?
which means this should raise an error, because value of argument1 is overriden, by default, argparse just overrides the value and continues like nothing happened... Is there any smart way how to disable this behaviour?
推荐答案
我不认为有使用 argparse
的本地方法,但幸运的是,argparse
提供报告自定义错误的方法.最优雅的方法可能是定义一个自定义操作来检查重复项(如果有则退出).
I don't think there is a native way to do it using argparse
, but fortunately, argparse
offers methods to report custom errors. The most elegant way is probably to define a custom action that checks for duplicates (and exits if there are).
class UniqueStore(argparse.Action):
def __call__(self, parser, namespace, values, option_string):
if getattr(namespace, self.dest, self.default) is not self.default:
parser.error(option_string + " appears several times.")
setattr(namespace, self.dest, values)
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--foo', action=UniqueStore)
args = parser.parse_args()
(阅读关于自定义操作的文档)
另一种方法是使用 append 操作并计算列表的 len.
Another way is to use the append action and count the len of the list.
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--foo', action='append')
args = parser.parse_args()
if len(args.foo) > 1:
parser.error("--foo appears several times.")
这篇关于argparse - 禁用相同的参数出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!