python-click:格式化帮助文本

标签 python command-line-interface python-click

这个问题是关于 click封装:

  1. 未按预期显示长帮助文本。
  2. 我也尝试过使用 /b 但似乎没有太大影响。
  3. cmdpowershell 对于相同的代码都有不同的结果,为什么?

Screen Shot of Problem

代码:

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

最佳答案

如果您 Hook click.formatting.wrap_text,您可以更改 click.Command.get_help 使用的行包装器的行为。

代码

由于您已经从 click.Command 继承,我们可以构建自己的 get_help() 版本来 Hook 行包装器,如下所示:

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 是一个设计良好的 OO 框架。 @click.command() 装饰器通常会实例化 click.Command 对象,但允许使用 cls 参数覆盖此行为。因此,在我们自己的类中继承 click.Command 并覆盖所需的方法是一件相对容易的事情。

在本例中,我们重写 click.Command.get_help()。然后,在 get_help() 中,我们 Hook click.formatting.wrap_text()。然后,在我们的钩子(Hook)中,我们将 preserve_paragraphs 标志设置为 True。此外,我们将所有 \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.

关于python-click:格式化帮助文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55585564/

相关文章:

python - pickle 错误: Can't pickle <class 'module' >: attribute lookup module on builtins failed

python - 如何使用 Python 的计时器一次读取一个字符的键盘输入

python-3.x - python3的编码问题并单击包

Python 点击​​ : Having the group execute code AFTER a command

python - main 方法上出现意外缩进

python - 显示时间进度

python - 让事件处理函数创建持久的 PYQT4 对象

windows - 复制 *.ext *.ex_ 不适用于绝对路径

linux - shell 中的命令复制 (cp)

rust - 在没有 cargo run 的情况下运行 Rust 程序