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
Allowing specific values for an Argparse argument
提问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.
这并不是特别困难,而是它看起来很混乱。

