Choice 选项有一个 case_sensitive 布尔参数,可用于允许混合大小写选择接受,例如:
@click.option('-c', '--choices', type=click.Choice(['V1', 'V2'], case_sensitive=False))
测试代码:
import click
@click.command(name='test')
@click.option('-c', '--choices', type=click.Choice(['V1', 'V2'], case_sensitive=False))
def test(choices):
click.echo(f'Choices: {choices}')
if __name__ == "__main__":
commands = (
'',
'-c v1',
'-c V1',
'-c V2',
'--help',
)
import sys, time
time.sleep(1)
print('Click Version: {}'.format(click.__version__))
print('Python Version: {}'.format(sys.version))
for cmd in commands:
try:
time.sleep(0.1)
print('-----------')
print('> ' + cmd)
time.sleep(0.1)
test(cmd.split())
except BaseException as exc:
if str(exc) != '0' and \
not isinstance(exc, (click.ClickException, SystemExit)):
raise
测试结果:
Click Version: 7.1.2
Python Version: 3.8.10 (tags/v3.8.10:3d8993a, May 3 2021, 11:48:03) [MSC v.1928 64 bit (AMD64)]
-----------
>
Choices: V1
-----------
> -c v1
Choices: V1
-----------
> -c V1
Choices: V1
-----------
> -c V2
Choices: V2
-----------
> --help
Usage: test_code.py [OPTIONS]
Options:
-c, --choices [V1|V2]
--help Show this message and exit.