2017-04-03 39 views
0

我有一個utility它允許用戶讀取他們的~/.aws/credentials文件和導出環境變量。可選的子分析器?

目前,CLI界面看起來是這樣的:

usage: aws-env [-h] [-n] profile 

Extract AWS credentials for a given profile as environment variables. 

positional arguments: 
    profile   The profile in ~/.aws/credentials to extract credentials 
        for. 

optional arguments: 
    -h, --help  show this help message and exit 
    -n, --no-export Do not use export on the variables. 

我想在這裏做什麼的是提供一個ls子分析器,將允許用戶列出他們~/.aws/credentials有效的配置文件名稱。

的接口將是這樣的:

$ aws-env ls 
profile-1 
profile-2 

...等等。有沒有一種方法可以在argparse中本地執行此操作,以便在我的-h輸出中顯示一個選項,這表明ls是一個有效的命令?

+0

你有沒有真的試圖加入子分析器? https://docs.python.org/3/library/argparse.html#sub-commands – jonrsharpe

+0

我需要一個「ls」命令的subparser和一個通用的subparser來匹配單個配置文件名稱,可以是任何東西。那可能嗎? –

+0

你試過了嗎?發生了什麼?做任何研究?例如。 http://stackoverflow.com/q/8668519/3001761 – jonrsharpe

回答

1

如果您使用subparsers路線,則可以定義兩個解析器'ls'和'extract'。 'ls'不會有任何爭論; '提取'將採取一個位置,'配置文件'。

子分析器是可選的,(Argparse with required subparser),但需要'profile',如當前定義的那樣。

另一種方法是定義兩個可選項,並省略位置。

'-ls', True/False, if True to the list 
'-e profile', if not None, do the extract. 

或者你可以離開這個位置profile,但要選購(NARGS = '?')。

另一種可能性是在解析後查看profile的值。如果它是'ls'這樣的字符串,那麼列出而不是提取。這感覺像最乾淨的選擇,但是,這種用法不會記錄這一點。


parser.add_argument('-l','--ls', action='store_true', help='list') 
parser.add_argument('profile', nargs='?', help='The profile') 

sp = parser.add_subparsers(dest='cmd') 
sp.add_parser('ls') 
sp1 = sp.add_parser('extract') 
sp1.add_argument('profile', help='The profile') 

一個必需的互斥組

gp = parser.add_mutually_exclusive_group(required=True) 
gp.add_argument('--ls', action='store_true', help='list') 
gp.add_argument('profile', nargs='?', default='adefault', help='The profile') 

生產:

usage: aws-env [-h] [-n] (--ls | profile) 
+0

TL; DR這不是真的可行,但有解決方法。 –