可选的子解析器?

Optional subparsers?

我有一个 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 是一个有效的命令?

如果你走 subparsers 路线,你可以定义两个解析器,'ls' 和 'extract'。 'ls' 不会有任何争论; 'extract' 会占用一个位置,'profile'。

子解析器是可选的,(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'这样的字符串,则list而不是extract。这感觉是最干净的选择,但是,用法不会记录这一点。


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)