Python argparse:如何检测重复的可选参数? [英] Python argparse : how to detect duplicated optional argument?

查看:19
本文介绍了Python argparse:如何检测重复的可选参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有可选参数的 argparse,但我想避免这样的事情:script.py -a 1 -b -a 2这里我们有两次可选参数'a',只返回第二个参数.我想获得两个值或获得错误消息.我应该如何定义论点?

I'm using argparse with optional parameter, but I want to avoid having something like this : script.py -a 1 -b -a 2 Here we have twice the optional parameter 'a', and only the second parameter is returned. I want either to get both values or get an error message. How should I define the argument ?

这是代码:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-a', dest='alpha', action='store', nargs='?')
parser.add_argument('-b', dest='beta', action='store', nargs='?')

params, undefParams = self.parser.parse_known_args()

推荐答案

append action 将收集重复使用的值在一个列表中

append action will collect the values from repeated use in a list

parser.add_argument('-a', '--alpha', action='append')

产生一个 args 命名空间,如:

producing an args namespace like:

namespace(alpha=['1','3'], b='4')

解析后,您可以检查args.alpha,并接受或抱怨值的数量.parser.error('repeated -a') 可用于发出 argparse 样式的错误消息.

After parsing you can check args.alpha, and accept or complain about the number of values. parser.error('repeated -a') can be used to issue an argparse style error message.

您可以在自定义 Action 类中实现类似的功能,但这需要了解此类类的基本结构和操作.我想不出任何可以在 Action 中完成的事情,也不能在之后的附加列表中完成.

You could implement similar functionality in a custom Action class, but that requires understanding the basic structure and operation of such a class. I can't think anything that can be done in an Action that can't just as well be done in the appended list after.

https://stackoverflow.com/a/23032953/901925 是一个无重复自定义的答案<代码>操作.

https://stackoverflow.com/a/23032953/901925 is an answer with a no-repeats custom Action.

为什么要使用带有标记参数的 nargs='?' 像这样?如果没有 const 参数,这几乎是无用的(请参阅文档中的 nargs=? 部分).

Why are you using nargs='?' with flagged arguments like this? Without a const parameter this is nearly useless (see the nargs=? section in the docs).

另一个类似的 SO:Python argparse 与 nargs 行为不正确

这篇关于Python argparse:如何检测重复的可选参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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