【发布时间】: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