【问题标题】:Optional subparsers?可选的子解析器?
【发布时间】:2017-08-28 19:23:43
【问题描述】:

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

【问题讨论】:

  • 您是否真的尝试过添加子解析器? docs.python.org/3/library/argparse.html#sub-commands
  • 我需要一个用于ls 命令的子解析器和一个用于匹配单个配置文件名称的通用子解析器,它可以是任何东西。这可能吗?
  • 我不确定我关注的是 ls 子命令,结果是输出 profile-1\nprofile-2 或者您希望 profile-X 成为 arg 解析器的一部分?如果是后者,鉴于您没有提供凭证文件的选项,只需阅读它并提取配置文件并将它们添加到解析器。
  • @jonsharpe - 你的 SO 链接基本上说,在混合位置参数和子解析器时要小心。根据我的经验,当主解析器的所有参数都被标记(可选)时,子解析器工作得最好。

标签: python-2.7 python-3.x argparse


【解决方案1】:

如果你走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'这样的字符串,则列出而不是提取。这感觉是最干净的选择,但是,用法不会记录这一点。


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)

【讨论】:

  • TL;DR 这不太可能,但有一些解决方法。
猜你喜欢
  • 2020-09-26
  • 2012-01-21
  • 2017-05-07
  • 2019-05-04
  • 2013-10-09
  • 1970-01-01
  • 2013-12-21
  • 2015-12-11
相关资源
最近更新 更多