Python-click: форматирование текста справки

Этот вопрос касается пакета нажмите:

  1. Длинный текст справки не отображается должным образом.
  2. Я также пытался использовать /b, но, похоже, это не сильно влияет.
  3. cmd и powershell дают разные результаты для одного и того же кода, почему?

Python-click: форматирование текста справки

КОД:

import click


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]] 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: 'gs',  # generator_string
    2: 'nosp',  # number_of_sample_points
    3: 'nocp',  # 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), metavar='FILE', help = """\b
    Path to csv file""" )
@click.option('--doe', required=True, type=int, help = """
\b
Select DOE algorithm:   
1 Full factorial 
2 2-level fractional factorial
3 Plackett-Burman
4 Sukharev grid
5 Box-Behnken
6 Box-Wilson (Central-composite) with center-faced option
7 Box-Wilson (Central-composite) with center inscribed
8 Box-Wilson (Central-composite) with centser-circumscribed option
9 Latin hypercube (simple)
10 Latin hypercube (space-filling)
11 Random k-means cluster
12 Maximin reconstruction
13 Halton sequence based
14 Uniform random matrix
...
""",)
@click.option( '--gs', required=False, type=str, help = """\b
    Generator string for the fractional factorial build""")
@click.option(  '--nosp', required=False, type=int, help = """\b
    Number of random sample points""")
@click.option( '--nocp', required=False, type=int, help = """\b
    Number of center points to be repeated (if more than one):""")
def main(input, doe, gs, nosp, nocp):
    click.echo('input: {}'.format(input))
    click.echo('doe: {}'.format(doe))
    click.echo('generator_string: {}'.format(gs))
    click.echo('Num of sample_points: {}'.format(nosp))
    click.echo('Num of center_points: {}'.format(nocp))


if __name__ == "__main__":
    main()

Какой результат вы ищете? (4) в CMD явно странно, но остальные (на первый взгляд) кажутся разумными.

Stephen Rauch 09.04.2019 07:43

4 и 11 в CMD оба перегружены. Я ожидал одну длинную строку, так как у CMD много свободного места справа.

django 09.04.2019 08:00

Но для начала будет очень признательна последовательная печать как на powershell, так и на cmd.

django 09.04.2019 08:00
Почему в 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 может стать мощным инструментом для создания эффективных и масштабируемых веб-приложений.
2
3
3 204
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

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

Если вы подключите click.formatting.wrap_text, вы можете изменить поведение обертки строки, которую использует click.Command.get_help.

Код

Поскольку вы уже унаследовали от click.Command, мы можем создать собственную версию get_help(), чтобы подключить оболочку строки, например:

def command_required_option_from_option(require_name, require_map):

    class CommandOptionRequiredClass(click.Command):

        def get_help(self, ctx):
            orig_wrap_test = click.formatting.wrap_text

            def wrap_text(text, width=78, initial_indent='',
                          subsequent_indent='',
                          preserve_paragraphs=False):
                return orig_wrap_test(text.replace('\n', '\n\n'), width,
                                      initial_indent=initial_indent,
                                      subsequent_indent=subsequent_indent,
                                      preserve_paragraphs=True
                                      ).replace('\n\n', '\n')

            click.formatting.wrap_text = wrap_text
            return super(CommandOptionRequiredClass, self).get_help(ctx)

    return CommandOptionRequiredClass

Как это работает?

Это работает, потому что click — это хорошо спроектированная объектно-ориентированная среда. Декоратор @click.command() обычно создает экземпляр объекта click.Command, но позволяет переопределить это поведение с помощью параметра cls. Таким образом, относительно легко наследоваться от click.Command в нашем собственном классе и переопределять нужные методы.

В этом случае мы переопределяем click.Command.get_help(). В наш get_help() мы затем цепляем click.formatting.wrap_text(). Затем в нашем хуке мы устанавливаем флаг preserve_paragraphs на True. Кроме того, мы replace() все \n с \n\n, поскольку именно так оригинал wrap_text() ожидает, что абзацы будут помечены.

Тестовый код:

import click

required_options = {
    1: 'gs',  # generator_string
    2: 'nosp',  # number_of_sample_points
    3: 'nocp',  # 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), 
              metavar='FILE', help = """\b
    Path to csv file""" )
@click.option('--doe', required=True, type=int, help = """
Select DOE algorithm:   
1 Full factorial 
2 2-level fractional factorial
3 Plackett-Burman
4 Sukharev grid
5 Box-Behnken
6 Box-Wilson (Central-composite) with center-faced option
7 Box-Wilson (Central-composite) with center inscribed
8 Box-Wilson (Central-composite) with center-circumscribed option
9 Latin hypercube (simple)
10 Latin hypercube (space-filling)
11 Random k-means cluster
12 Maximin reconstruction
13 Halton sequence based
14 Uniform random matrix
...
""",)
@click.option( '--gs', required=False, type=str, help = """\b
    Generator string for the fractional factorial build""")
@click.option(  '--nosp', required=False, type=int, help = """\b
    Number of random sample points""")
@click.option( '--nocp', required=False, type=int, help = """\b
    Number of center points to be repeated (if more than one):""")
def main(input, doe, gs, nosp, nocp):
    click.echo('input: {}'.format(input))
    click.echo('doe: {}'.format(doe))
    click.echo('generator_string: {}'.format(gs))
    click.echo('Num of sample_points: {}'.format(nosp))
    click.echo('Num of center_points: {}'.format(nocp))

if __name__ == "__main__":
    main(['--help'])

Результаты:

Usage: test.py [OPTIONS]

Options:
  --input FILE    
                  Path to csv file  [required]
  --doe INTEGER   Select DOE algorithm:
                  1 Full factorial
                  2 2-level fractional factorial
                  3 Plackett-Burman
                  4 Sukharev grid
                  5 Box-Behnken
                  6 Box-Wilson (Central-composite) with center-faced option
                  7 Box-Wilson (Central-composite) with center inscribed
                  8 Box-Wilson (Central-composite) with center-circumscribed
                  option
                  9 Latin hypercube (simple)
                  10 Latin hypercube (space-filling)
                  11 Random k-means cluster
                  12 Maximin reconstruction
                  13 Halton sequence based
                  14 Uniform random matrix
                  ...  [required]
  --gs TEXT       
                  Generator string for the fractional factorial build
  --nosp INTEGER  
                  Number of random sample points
  --nocp INTEGER  
                  Number of center points to be repeated (if more than one):
  --help          Show this message and exit.

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