Python 允许 Argparse 参数的特定值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15836713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:07:33  来源:igfitidea点击:

Allowing specific values for an Argparse argument

pythonargparse

提问by Moshe

Is it possible to require that an argparseargument be one of a few preset values?

是否可以要求argparse参数是几个预设值之一?

My current approach would be to examine the argument manually and if it's not one of the allowed values call print_help()and exit.

我目前的方法是手动检查参数,如果它不是允许的值之一,则调用print_help()和退出。

Here's the current implementation:

这是当前的实现:

...
parser.add_argument('--val',
                    help='Special testing value')

args = parser.parse_args(sys.argv[1:])
if args.val not in ['a', 'b', 'c']:
    parser.print_help()
    sys.exit(1)

It's not that this is particularly difficult, but rather that it appears to be messy.

这并不是特别困难,而是它看起来很混乱。

采纳答案by Moshe

An argparse argument can be limited to specific values with the choicesparameter:

argparse 参数可以限制为具有choices参数的特定值:

...
parser.add_argument('--val',
                    choices=['a', 'b', 'c'],
                    help='Special testing value')

args = parser.parse_args(sys.argv[1:])

See the docsfor more details.

有关更多详细信息,请参阅文档