蟒蛇点击:格式化帮助文本(python-click: formatting help text)

2019-09-28 01:48发布

这个问题是关于点击包:

  1. 根据需要不显示帮助的长文。
  2. 我尝试使用/b为良好,但似乎并没有影响到很多。
  3. cmdpowershell都有相同的代码不同的结果,为什么?

码:

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

Answer 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

这是如何运作的?

这工作,因为点击是一个精心设计的OO框架。 在@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.


文章来源: python-click: formatting help text