【问题标题】:Python commandline argument that can be either Empty or from a Choice listPython 命令行参数,可以是 Empty 或来自选择列表
【发布时间】:2020-08-08 17:53:48
【问题描述】:

我正在编写一个用于控制 Docker 映像构建的脚本。 我目前支持一个或多个 Centos 基础镜像和一个或多个 Debian。 我希望“--centos”或“--debian”默认为最新版本。 但是如果用户想要构建一个较旧的副本,那么这应该来自一个选择列表。 因此,我正在寻找以下混合体: parser.add_argument('--centos', 选择=['centos-6','centos-7']) 和 parser.add_argument('--centos')

所以我可以像这样运行脚本:

python dobuild.py --centos #would build the latest centos in the list

python dobuild.py --centos centos-6 #would build the older copy

但是

python dobuild.py --centos centos-5 #would return an 'invalid choice' error

我试过choices=['centos-6','centos-7','']choices=['centos-6','centos-7', []]

为了完整性:python dobuild.py --centos --debian #would build the latest centos AND latest debian in the list 等等 。 . .

【问题讨论】:

  • 我不知道有任何包含电池的方式来拥有这种精确的语法,但这不是很好,对吧?为什么不允许使用一系列标志 --centos--centos-6--centos-7 等?
  • 不错的想法@AdamSmith 需要比当前方法更详细一些,因为“有效”列表来自名为 IMAGES 的字典结构:parser.add_argument('--centos', choices=list(IMAGES['centos'].keys()), help=f"""Image for compiling on Centos Linux (default={list(IMAGES['centos'])[0]})""", required=required)

标签: python command-line-arguments argparse


【解决方案1】:

要使用默认值添加此可选参数,您可以使用nargs='?'const='<default>'Here in the docs

请注意,对于可选参数,还有一种情况 - 选项字符串存在但后面没有命令行参数。在这种情况下,将产生来自 const 的值:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--centos', choices=['centos-6', 'centos-7'], nargs='?', const='centos-7')

使用这个解析器:

>>> parser.parse_args([])
Namespace(centos=None)
>>> parser.parse_args(['--centos'])
Namespace(centos='centos-7')
>>> parser.parse_args(['--centos', 'centos-6'])
Namespace(centos='centos-6')

【讨论】:

  • 哇 @Iain Shelvington 感谢您的出色回答和实际代码。很有帮助。
猜你喜欢
  • 2015-07-05
  • 2013-07-10
  • 2012-03-08
  • 2014-02-02
  • 2012-10-06
  • 2020-05-04
  • 2023-03-10
  • 2017-04-04
  • 1970-01-01
相关资源
最近更新 更多