argparse-禁用相同的参数出现 [英] argparse - disable same argument occurrences

查看:126
本文介绍了argparse-禁用相同的参数出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用argparse在一个命令行中禁用相同的参数出现

I'm trying to disable same argument occurences within one command line, using argparse

./python3 --argument1=something --argument2 --argument1=something_else

这意味着应该引发一个错误,因为参数1的值被覆盖,默认情况下,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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆