Argparse:如何在其他选项存在的情况下禁止某些选项 - Python [英] Argparse: How to disallow some options in the presence of others - 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')
,但对于更复杂的依赖图(例如,--bat
需要 --bar
和 --baz
),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屋!