Allowing specific values for an Argparse argument [duplicate]

北慕城南 提交于 2019-12-04 14:54:32

问题


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

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

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.


回答1:


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

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

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

See the docs for more details.



来源:https://stackoverflow.com/questions/15836713/allowing-specific-values-for-an-argparse-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!