python - python 中不区分大小写的选择

标签 python command-line-interface python-click

我有一个带有子命令测试的 python-click CLI。函数 test 中的选项 choices 接受 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选项有一个 case_sensitive可用于允许混合大小写选择接受的 bool 参数,例如:

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

关于python - python 中不区分大小写的选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67926744/

相关文章:

python - 如何使用python在递归中正确返回值?

python - 如何按反向排序元组,但不反向打破关系? (Python)

linux - 哪个是用于 virtualbox 的轻量级 linux?

linux - 从 CLI 检查 Berkeley DB 文件

node.js - 命令行的日期选择器

Python Click - 从配置文件提供参数和选项

python - 使用 Python 的 Facebook API。如何打印出所有帖子的评论?

python - 使用 python-click 将未指定的选项添加到 cli 命令

python - 单击 : Use another function in chained commands with context object

python - pip install -U PySide 错误