python 中不区分大小写的选项点击

Case Insensitive choices in python click

我有一个带有子命令测试的 python-click CLI。函数 choices 中的选项 test 接受 V1V2(大写)。

@click.command(name='test')
@click.option('-c', '--choices', type=click.Choice(['V1', 'V2']), default='V1')
def test(choices):
    print(choices)

如果用户不小心键入 v1(小写)而不是 V1(大写),那么我会从点击库中收到错误消息。

Error: Invalid value for "-c" / "--choices": invalid choice: v1. (choose from V1, V2)

我怎样才能实现不区分大小写的 click.Choice 实现,以便即使我键入 v1(小写)我也会在函数中得到 V1(大写)?

可用于允许混合大小写选择接受的 Choice option has a 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.