2016-04-25 100 views
0

我創建了一個CLI規範與docopt出於某種原因,我不得不重寫然而偉大工程,它argparsemutually_exclusive_group與可選的位置參數

Usage: 
    update_store_products <store_name>... 
    update_store_products --all 

    Options: 
     -a --all  Updates all stores configured in config 

如何做到這一點?

什麼是重要的,我不希望有這樣的事情:

update_store_products [--all] <store_name>... 

我認爲這將是相當類似:

update_store_products (--all | <store_name>...) 

我試圖用add_mutually_exclusive_group,但我遇到錯誤:

ValueError: mutually exclusive arguments must be optional 

回答

5

首先,你應該包括the shortest code necessary to reproduce the error in the question itself。沒有它,答案只是黑暗中的一個鏡頭。

現在,我敢打賭你argparse定義看起來有點像這樣:

parser = ArgumentParser() 
group = parser.add_mutually_exclusive_group(required=True) 
group.add_argument('--all', action='store_true') 
group.add_argument('store_name', nargs='*') 

的互斥組參數必須是可選的,因爲它不會太大意義有需要在那裏進行論證,因爲該團體可能只有這樣的論點。單獨使用nargs='*'是不夠的 - 創建的actionrequired屬性將爲True - 說服互斥組參數是真正可選的。你所要做的是添加默認:

parser = ArgumentParser() 
group = parser.add_mutually_exclusive_group(required=True) 
group.add_argument('--all', action='store_true') 
group.add_argument('store_name', nargs='*', default=[]) 

這將導致:

[~]% python2 arg.py 
usage: arg.py [-h] (--all | store_name [store_name ...]) 
arg.py: error: one of the arguments --all store_name is required 

[~]% python2 arg.py --all 
Namespace(all=True, store_name=[]) 

[~]% python2 arg.py store1 store2 store3 
Namespace(all=False, store_name=['store1', 'store2', 'store3'])