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()

Вы можете сделать 3 возможных значения --doe как подкоманды. Каждая подкоманда может иметь совершенно разные параметры.

gdlmx 09.04.2019 04:37

Да, но у меня нет таких команд, как синхронизация, у меня есть только параметры или аргументы, см. мои примеры, также у алгоритмов очень длинное имя, поэтому я использую числа. есть идеи ?

django 09.04.2019 05:10
Почему в Python есть оператор "pass"?
Почему в Python есть оператор "pass"?
Оператор pass в Python - это простая концепция, которую могут быстро освоить даже новички без опыта программирования.
Некоторые методы, о которых вы не знали, что они существуют в Python
Некоторые методы, о которых вы не знали, что они существуют в Python
Python - самый известный и самый простой в изучении язык в наши дни. Имея широкий спектр применения в области машинного обучения, Data Science,...
Основы Python Часть I
Основы Python Часть I
Вы когда-нибудь задумывались, почему в программах на Python вы видите приведенный ниже код?
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
Алиса и Боб имеют неориентированный граф из n узлов и трех типов ребер:
Оптимизация кода с помощью тернарного оператора Python
Оптимизация кода с помощью тернарного оператора Python
И последнее, что мы хотели бы показать вам, прежде чем двигаться дальше, это
Советы по эффективной веб-разработке с помощью Python
Советы по эффективной веб-разработке с помощью Python
Как веб-разработчик, Python может стать мощным инструментом для создания эффективных и масштабируемых веб-приложений.
7
2
5 492
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Я бы предложил сделать это с помощью специального класса 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.

Неуместный вопрос, но click не поддерживает camelCase? | Если я пишу @click.option('--generatorString') это не работает

django 09.04.2019 06:22

также я думаю, что мне не нужно , is_eager=True для дополнительных опций .. верно ??

django 09.04.2019 06:23

Щелчок нормализует имена. Я сделал небольшое редактирование, чтобы разрешить верблюжий случай. Вам все равно нужно будет main() взять сплющенный чехол, но для пользователя это будет camelCase.

Stephen Rauch 09.04.2019 06:29

задал здесь вопрос по форматированию, stackoverflow.com/questions/55585564/…

django 09.04.2019 07:21

Другие вопросы по теме