2017-08-09 41 views
0

我使用python3.4
問題是指https://docs.python.org/3/library/argparse.html我該如何標記cli arg以依賴另一個arg存在?

如果我想要一個ARG如果這兩個中的一個缺失--with_extra_actions總是acompany --arg1--arg2並給出錯誤信息?

例子:
command --arg1 --with_extra_actions這應該工作
command --arg2 --with_extra_actions這應該工作
command --with_extra_actions這應該失敗信息的錯誤。

我現在正在代碼本身。沒有問題,但有沒有一個固有的方式爲​​lib做到這一點?

+0

有一個互斥的分組,但沒有相互包含的分組。 Subparsers適用於某些情況。否則,解析後進行自己的測試是您的最佳選擇。 – hpaulj

+0

有時我們可以定義'--arg1'來獲取多個參數,2,'+'等,然後我們不需要定義額外的動作。 – hpaulj

回答

0

您可以使用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 

希望這有助於。