【问题标题】:Case Insensitive choices in python clickpython中不区分大小写的选择单击
【发布时间】:2021-08-27 19:00:02
【问题描述】:

我有一个带有子命令 test 的 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(大写)?

【问题讨论】:

    标签: python command-line-interface python-click


    【解决方案1】:

    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.
    

    【讨论】:

      猜你喜欢
      • 2014-05-24
      • 1970-01-01
      • 2011-05-16
      • 1970-01-01
      • 2018-04-28
      • 2014-05-22
      • 2015-11-10
      • 2019-11-12
      • 1970-01-01
      相关资源
      最近更新 更多