不区分大小写的 argparse 选择 [英] Case insensitive argparse choices

查看:36
本文介绍了不区分大小写的 argparse 选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以不区分大小写的方式检查argparse选项?

Is it possible to check argparse choices in case-insensitive manner?

import argparse
choices = ["win64", "win32"]
parser = argparse.ArgumentParser()
parser.add_argument("-p", choices=choices)
print(parser.parse_args(["-p", "Win32"]))

结果:

usage: choices.py [-h] [-p {win64,win32}]
choices.py: error: argument -p: invalid choice: 'Win32' (choose from 'win64','win32')

推荐答案

通过使用将参数转换为小写

Transform the argument into lowercase by using

type = str.lower

用于 -p 开关.

此解决方案由 chepner评论.我之前提出的解决方案是

This solution was pointed out by chepner in a comment. The solution I proposed earlier was

type = lambda s : s.lower()

这也是有效的,但使用 str.lower 更简单.

which is also valid, but it's simpler to just use str.lower.

这篇关于不区分大小写的 argparse 选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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