创建带有仅在默认值为空时显示的提示的Click.Option [英] Creating a Click.Option with prompt that shows only if default value is empty

查看:63
本文介绍了创建带有仅在默认值为空时显示的提示的Click.Option的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下选项:

@cli.command()
@click.option('--param', default=lambda: get_value(), prompt="Enter Param")

正常的行为是单击以显示提示输入param的值并显示默认值(您可以通过输入ENTER保留该值).

Normal behavior is for click to show a prompt to enter a value for param and display the default value (and you can just ENTER through it to preserve that).

相反,我希望param提示仅在get_value()返回None或某些预定义的显示"值时显示,但是对于get_value()的任何Truthy/Other值,单击将不显示提示输入此选项,然后运行命令或移至下一个提示.

Instead I'd like the param prompt to only show if get_value() returns None or some pre-defined "show" value, but for any Truthy/Other value for get_value() click will not show the prompt for this option and run the command or move to the next prompt.

推荐答案

这可以通过使用click.Option.get_default()click.Option.prompt_for_value()方法,例如:

This can be done by over riding the click.Option.get_default() and the click.Option.prompt_for_value() methods like:

import click

class OptionPromptNull(click.Option):
    _value_key = '_default_val'

    def get_default(self, ctx):
        if not hasattr(self, self._value_key):
            default = super(OptionPromptNull, self).get_default(ctx)
            setattr(self, self._value_key, default)
        return getattr(self, self._value_key)

    def prompt_for_value(self, ctx):        
        default = self.get_default(ctx)

        # only prompt if the default value is None
        if default is None:
            return super(OptionPromptNull, self).prompt_for_value(ctx)

        return default

使用自定义类:

然后使用自定义类,将其作为cls参数传递给选项装饰器,例如:

Using Custom Class:

Then to use the custom class, pass it as the cls argument to the option decorator like:

@click.command()
@click.option('--param', cls=OptionPromptNull,
              default=lambda: get_value(), prompt="Enter Param")
def cli(param):
    click.echo("param: '{}'".format(param))

测试代码:

@click.command()
@click.option('--param1', cls=OptionPromptNull,
              default=lambda: get_value_none(), prompt="Enter Param1")
@click.option('--param2', cls=OptionPromptNull,
              default=lambda: get_value_one(), prompt="Enter Param2")
def cli(param1, param2):
    click.echo("param1: '{}'".format(param1))
    click.echo("param2: '{}'".format(param2))


def get_value_none():
    return None

def get_value_one():
    return 1

cli([])

结果:

Enter Param1: 23
param1: '23'
param2: '1'

这篇关于创建带有仅在默认值为空时显示的提示的Click.Option的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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