Python 可以为空或来自选择列表的命令行参数

Python commandline argument that can be either Empty or from a Choice list

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

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

Note that for optional arguments, there is an additional case - the option string is present but not followed by a command-line argument. In this case the value from const will be produced:

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')