【问题标题】:How can I mark a cli arg to be dependant on another arg existance?如何将 cli arg 标记为依赖于另一个 arg 存在?
【发布时间】:2018-01-17 14:32:20
【问题描述】:

我正在使用 python3.4
问题指https://docs.python.org/3/library/argparse.html

如果我希望 arg --with_extra_actions 始终伴随 --arg1--arg2 并在缺少这两者之一时给出错误消息?

示例:
command --arg1 --with_extra_actions 应该可以工作
command --arg2 --with_extra_actions 应该可以工作
command --with_extra_actions 这应该会失败并显示信息错误。

我现在正在代码本身中执行此操作。那里没有问题,但是argparse lib 有没有内在的方法来做到这一点?

【问题讨论】:

  • 有一个互斥的分组,但没有一个互包含的分组。子解析器适用于某些情况。否则,在解析后进行自己的测试是您的最佳选择。
  • 有时我们可以定义--arg1来接受多个参数,2、'+'等。然后我们就不需要定义额外的动作了。

标签: python python-3.x command-line dependencies argparse


【解决方案1】:

您可以使用add_mutually_exclusive_group 进行操作。这里的例子(test.py):

import argparse
import sys


parser = argparse.ArgumentParser(prog='our_cmd')
# with_extra_actions is always required
parser.add_argument(
    '--with_extra_actions',
    required=True,
    action='store_false'
)

# only one argument from group is available
# group is required - one from possible arguments is required
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--arg1', action='store_true')
group.add_argument('--arg2', action='store_true')

parser.parse_args(sys.argv[1:])

现在让我们检查一下我们的脚本:

python test.py --with_extra_actions
usage: our_cmd [-h] --with_extra_actions (--arg1 | --arg2)
our_cmd: error: one of the arguments --arg1 --arg2 is required

让我们试试arg1arg2

python test.py --arg1 --arg2 --with_extra_actions
usage: our_cmd [-h] --with_extra_actions (--arg1 | --arg2)
our_cmd: error: argument --arg2: not allowed with argument --arg1

没有任何错误:

python test.py --arg1 --with_extra_actions
python test.py --arg2 --with_extra_actions

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2011-12-11
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 2015-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多