python argparse同时预防长标志
我有这个代码:
parser = argparse.ArgumentParser()
parser.add_argument('-L', '--list', action='store_true', help='list options')
args = parser.parse_args()
我想要这样的:
$./example.py --list
或者
$./example.py -L
不:
$./example -L --list # or --list -L
有没有一种优雅的方法来避免同时使用两个标志?
I have this code:
parser = argparse.ArgumentParser()
parser.add_argument('-L', '--list', action='store_true', help='list options')
args = parser.parse_args()
I want this:
$./example.py --list
or
$./example.py -L
but not:
$./example -L --list # or --list -L
Is there an elegant way to avoid that both flags being used at the same time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以组成一个互斥的群体。这不是理想的选择,因为您最终会重复每个参数,但是如果需要,可以将其包裹到助手功能中。
如果您想稍微漂亮一点(避免重复自己),则可以做类似的事情:
You can form a mutually exclusive group. That isn't ideal, since you'll end up repeating arguments to each, but that can be wrapped up into a helper function if need be.
If you wanted to pretty this up a bit (to avoid repeating yourself), you could do something like: