您可以使用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
讓我們arg1
和arg2
嘗試:
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
希望這有助於。
有一個互斥的分組,但沒有相互包含的分組。 Subparsers適用於某些情況。否則,解析後進行自己的測試是您的最佳選擇。 – hpaulj
有時我們可以定義'--arg1'來獲取多個參數,2,'+'等,然後我們不需要定義額外的動作。 – hpaulj