Python argparse 互斥参数
我怎样才能让 argparse 做类似的事情:
[ 'all' | [ pos1 [ pos2 [ pos3 ...]]]] --some --other --flags
其中 all
是保留字(如果不需要 -
前缀,则将其作为标志是不行的)
第二: 是否可以为命名参数设置一些别名,例如 -h
和 --help
表示相同的选项?也许我应该尝试使用add_mutually_exclusive_group()
?
How can I make argparse do something like:
[ 'all' | [ pos1 [ pos2 [ pos3 ...]]]] --some --other --flags
where all
is a reserved word (making it a flag would not be ok if it doesn't need a -
prefix)
Second:
is it possible to have some aliases for named parameters like -h
and --help
meaning the same option? Maybe I should try with add_mutually_exclusive_group()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
add_mutually_exclusive_group() 正是为此而设计的 - 您正在尝试添加一个互斥组。
关于你的问题的第二部分,这应该做你想要的:(
注意:你的问题有点令人困惑 - 有两个问题,第二个问题直接进入关于第一个问题的另一个句子。更不用说大量错别字...我会尽力提供帮助,但您提出的问题越清楚,我们就能越清楚地回答您。)
更新
据我所知,互斥参数必须是必需的,但位置参数不能是必需的。因此,位置参数不能是互斥的(大概是因为否则解释器将无法分辨什么是什么)。就您的目的而言,我认为这并不重要,因为解释您的参数的代码实际上是相同的。
假设你可以按照你想要的方式去做,然后必须做这样的事情:
而如果你接受“全部”作为你的位置参数之一,你就必须这样做:
除非你有一些具体原因,我认为没有理由不采取后一种方式。
add_mutually_exclusive_group() is designed for exactly this - you are trying to add a mutually exclusive group.
In regards to the second part of your question, this should do what you want:
(Note: your question is a bit confusing - there are two questions there and the second question runs straight into another sentence about the first question. Not to mention the numerous typos... I'll try and help but the clearer you can make the question the clearer we can answer you.)
Update
As far as I can tell mutually exclusive arguments must be required but positional arguments cannot be required. Therefore positional arguments cannot be mutually exclusive (presumably because otherwise the interpreter wouldn't be able to tell what was what). For your purposes I don't think this really matters as the code that interprets your arguments would be practically the same either way.
Assuming you could do it the way you are trying to then have to do something like this:
Whereas if you accept "all" as one of your positional arguments you would have to do this:
Unless you have some specific reason, I see no reason not to do it the latter way.