允许Argparse参数的特定值 [英] Allowing specific values for an Argparse argument

查看:186
本文介绍了允许Argparse参数的特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我当前的方法是手动检查参数,如果不是允许的值之一,请调用 print_help() 并退出.

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.

这是当前的实现:

...
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.

推荐答案

使用有关更多详细信息,请参见文档.

See the docs for more details.

这篇关于允许Argparse参数的特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆