Argparse:如何在存在其他选项的情况下禁止某些选项-Python [英] Argparse: How to disallow some options in the presence of others - Python

查看:86
本文介绍了Argparse:如何在存在其他选项的情况下禁止某些选项-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下实用程序:

import argparse

parser = argparse.ArgumentParser(description='Do some action.')
parser.add_argument('--foo', '--fo', type=int, default=-1, help='do something foo')
parser.add_argument('--bar', '--br', type=int, default=-1, help='do something bar')
parser.add_argument('--baz', '--bz', type=int, default=-1, help='do something baz')
parser.add_argument('--bat', '--bt', type=int, default=-1, help='do something bat')

但是,如果使用-foo 选项,则应禁止使用-bat 选项,反之,则禁止使用-bat 选项仅在存在-bar -baz 的情况下使用.如何使用 argparse 完成此操作?当然,我可以添加一堆 if/else 块进行检查,但是有内置的 argparse 可以为我做到这一点吗?

However, if the --foo option is used, the --bat option should be disallowed, and conversely, the --bat option should only be used if --bar and --baz are present. How can I accomplish that using argparse? Sure, I could add a bunch of if / else blocks to check for that, but there's something built-in argparse that could do that for me?

推荐答案

您可以使用 parser.add_mutually_exclusive_group :

You can create mutually-exclusive groups of options with parser.add_mutually_exclusive_group:

group = parser.add_mutually_exclusive_group()
group.add_argument('--foo', '--fo', type=int, default=-1, help='do something foo')
group.add_argument('--bat', '--bt', type=int, default=-1, help='do something bat')

,但对于更复杂的依赖关系图(例如,需要-bar -baz -bat ),> argparse 不提供任何特定的支持.在内部平台效果的方向上,这太过分了.在 argparse 子系统中重新构建了完整编程语言的全部通用性.

, but for more complex dependency graphs (for example, --bat requiring --bar and --baz), argparse doesn't offer any specific support. That'd be going too far in the direction of the inner-platform effect, trying to rebuild too much of the full generality of a complete programming language within the argparse subsystem.

这篇关于Argparse:如何在存在其他选项的情况下禁止某些选项-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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