按住Python键单击:依赖于另一个选项的选项

python-click: dependent options on another option(按住Python键单击:依赖于另一个选项的选项)

本文介绍了按住Python键单击:依赖于另一个选项的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题与click程序包有关:我要设置我的命令,以便某些optional options依赖于特定的选项值,并且根据其值是必需的。

必需选项:

  1. 输入(输入文件)
  2. doe(整数,表示算法名称)

子选项: 如果是

  1. 等于1选项generator_string应变为required=True
  2. 等于2选项number_of_sample_points应变为required=True
  3. 等于3选项number_of_center_points应变为required=True

有效示例:

  1. --input ./input.txt --doe 1 --generator_string 1234
  2. --input ./input.txt --doe 2 --number_of_sample_points 3
  3. --input ./input.txt --doe 3 --number_of_center_points 2

代码:

import click


def check_output(ctx, param, value):
    if value == 1:
        if not ctx.params['generator_string']:
            setOptionAsRequired(ctx, 'generator_string')
    return value


def setOptionAsRequired(ctx, name):
    for p in ctx.command.params:
        if isinstance(p, click.Option) and p.name == name:
            p.required = True


@click.option('--input', required=True, type=click.Path(exists=True) )
@click.option('--doe', required=True, type=int, callback=check_output )
@click.option('--generator_string', required=False, type=str, is_eager=True)
@click.option('--number_of_sample_points', required=False, type=int, is_eager=True)
@click.option('--number_of_center_points', required=False, type=int, is_eager=True)
@click.command(context_settings=dict(max_content_width=800))
def main(input, doe, generator_string, number_of_sample_points, number_of_center_points):
    click.echo('is valid command')

if __name__ == '__main__':
    main()

推荐答案

我建议使用click.Command这样的自定义类来执行此操作:

自定义类:

def command_required_option_from_option(require_name, require_map):

    class CommandOptionRequiredClass(click.Command):

        def invoke(self, ctx):
            require = ctx.params[require_name]
            if require not in require_map:
                raise click.ClickException(
                    "Unexpected value for --'{}': {}".format(
                        require_name, require))
            if ctx.params[require_map[require].lower()] is None:
                raise click.ClickException(
                    "With {}={} must specify option --{}".format(
                        require_name, require, require_map[require]))
            super(CommandOptionRequiredClass, self).invoke(ctx)

    return CommandOptionRequiredClass

使用自定义类

required_options = {
    1: 'generator_string',
    2: 'number_of_sample_points',
    3: 'number_of_center_points',
}

@click.command(cls=command_required_option_from_option('doe', required_options))
...

这是如何工作的?

这是可行的,因为Click是一个设计良好的面向对象框架。@click.command()修饰符通常实例化click.Command对象,但允许使用cls参数覆盖此行为。因此,在我们自己的类中继承click.Command并覆盖所需的方法是一件相对容易的事情。

在这种情况下,我们覆盖click.Command.invoke(),然后在运行命令之前验证是否已设置所需选项

测试代码:

import click

required_options = {
    1: 'generator_string',
    2: 'number_of_sample_points',
    3: 'number_of_center_points',
}

@click.command(context_settings=dict(max_content_width=800),
               cls=command_required_option_from_option('doe', required_options))
@click.option('--input', required=True,
              type=click.Path(exists=True))
@click.option('--doe', required=True, type=int)
@click.option('--generator_string', required=False, type=str, is_eager=True)
@click.option('--number_of_sample_points', required=False, type=int,
              is_eager=True)
@click.option('--number_of_center_points', required=False, type=int,
              is_eager=True)
def main(input, doe, generator_string, number_of_sample_points,
         number_of_center_points):
    click.echo('input: {}'.format(input))
    click.echo('doe: {}'.format(doe))
    click.echo('generator_string: {}'.format(generator_string))
    click.echo('Num of sample_points: {}'.format(number_of_sample_points))
    click.echo('Num of center_points: {}'.format(number_of_center_points))


if __name__ == "__main__":
    commands = (
        '--input ./input.txt --doe 0',
        '--input ./input.txt --doe 1',
        '--input ./input.txt --doe 2',
        '--input ./input.txt --doe 3',
        '--input ./input.txt --doe 1 --generator_string 1234',
        '--input ./input.txt --doe 2 --number_of_sample_points 3',
        '--input ./input.txt --doe 3 --number_of_center_points 2',
        '',
        '--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)
            main(cmd.split())

        except BaseException as exc:
            if str(exc) != '0' and 
                    not isinstance(exc, (click.ClickException, SystemExit)):
                raise

结果:

Click Version: 6.7
Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
-----------
> --input ./input.txt --doe 0
Error: Unexpected value for --'doe': 0
-----------
> --input ./input.txt --doe 1
Error: With doe=1 must specify option --generator_string
-----------
> --input ./input.txt --doe 2
Error: With doe=2 must specify option --number_of_sample_points
-----------
> --input ./input.txt --doe 3
Error: With doe=3 must specify option --number_of_center_points
-----------
> --input ./input.txt --doe 1 --generator_string 1234
input: ./input.txt
doe: 1
generator_string: 1234
Num of sample_points: None
Num of center_points: None
-----------
> --input ./input.txt --doe 2 --number_of_sample_points 3
input: ./input.txt
doe: 2
generator_string: None
Num of sample_points: 3
Num of center_points: None
-----------
> --input ./input.txt --doe 3 --number_of_center_points 2
input: ./input.txt
doe: 3
generator_string: None
Num of sample_points: None
Num of center_points: 2
-----------
> 
Usage: test.py [OPTIONS]

Error: Missing option "--input".
-----------
> --help
Usage: test.py [OPTIONS]

Options:
  --input PATH                    [required]
  --doe INTEGER                   [required]
  --generator_string TEXT
  --number_of_sample_points INTEGER
  --number_of_center_points INTEGER
  --help                          Show this message and exit.

这篇关于按住Python键单击:依赖于另一个选项的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:按住Python键单击:依赖于另一个选项的选项

基础教程推荐