python-click:另一个选项上的从属选项

时间:2019-04-09 01:52:07

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

这个问题与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()

1 个答案:

答案 0 :(得分:3)

我建议使用一个自定义的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是一个设计良好的OO框架。 @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.