python-click:格式化帮助文本

2023-12-21

这个问题是关于click https://click.palletsprojects.com/en/7.x/包裹:

  1. 帮助的长文本未按预期显示。
  2. 我尝试使用/b也一样,但似乎影响不大。
  3. cmd and powershell相同的代码有不同的结果,为什么?

CODE:

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

如果你钩click.formatting.wrap_text您可以更改换行器的行为click.Command.get_help uses.

Code

既然你已经继承了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 是一个设计良好的 OO 框架。这@click.command()装饰器通常会实例化一个click.Command对象,但允许此行为被覆盖cls范围。所以继承是一件比较容易的事情click.Command在我们自己的班级中并超越所需的方法。

在本例中,我们重写 click.Command.get_help()。在我们的get_help()然后我们挂钩click.formatting.wrap_text()。然后在我们的钩子中设置preserve_paragraphs标记为True。另外我们replace() all \n with \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'])

Results:

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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python-click:格式化帮助文本 的相关文章

  • Python 类型提示 Dict 语法错误 可变默认值是不允许的。使用“默认工厂”

    我不知道为什么解释器会抱怨这个类型的字典 对于这两个实例 我得到一个 不允许可变默认值 使用默认工厂 语法错误 我使用的是 python 3 7 3 from dataclasses import dataclass from typing
  • 让 VoiceChannel.members 和 Guild.members 返回完整列表的问题

    每当我尝试使用 VoiceChannel members 或 Guild members 时 它都不会提供适用成员的完整列表 我从文本命令的上下文中获取 VoiceChannel 和 Guild 如下所示 bot command name
  • NLTK 2.0分类器批量分类器方法

    当我运行此代码时 它会抛出一个错误 我认为这是由于 NLTK 3 0 中不存在batch classify 方法 我很好奇如何解决旧版本中的某些内容在新版本中消失的此类问题 def accuracy classifier gold resu
  • VSCode Settings.json 丢失

    我正在遵循教程 并尝试将 vscode 指向我为 Scrapy 设置的虚拟工作区 但是当我在 VSCode 中打开设置时 工作区设置 选项卡不在 用户设置 选项卡旁边 我还尝试通过以下方式手动转到文件 APPDATA Code User s
  • 我应该使用 Python 双端队列还是列表作为堆栈? [复制]

    这个问题在这里已经有答案了 我想要一个可以用作堆栈的 Python 对象 使用双端队列还是列表更好 元素数量较少还是数量较多有什么区别 您的情况可能会根据您的应用程序和具体用例而有所不同 但在一般情况下 列表非常适合堆栈 append is
  • 从Django中具有外键关系的两个表中检索数据? [复制]

    这个问题在这里已经有答案了 This is my models py file from django db import models class Author models Model first name models CharFie
  • MongoEngine 查询具有以列表中指定的前缀开头的属性的对象的列表

    我需要在 Mongo 数据库中查询具有以列表中任何前缀开头的特定属性的元素 现在我有一段这样的代码 query mymodel terms term in query terms 并且这会匹配在列表 term 上有一个项目的对象 该列表中的
  • Tensorboard SyntaxError:语法无效

    当我尝试制作张量板时 出现语法错误 尽管开源代码我还是无法理解 我尝试搜索张量板的代码 但不清楚 即使我不擅长Python 我这样写路径C Users jh902 Documents logs因为我正在使用 Windows 10 但我不确定
  • Java 和 Python 可以在同一个应用程序中共存吗?

    我需要一个 Java 实例直接从 Python 实例数据存储中获取数据 我不知道这是否可能 数据存储是否透明 唯一 或者每个实例 如果它们确实可以共存 都有其单独的数据存储 总结一下 Java 应用程序如何从 Python 应用程序的数据存
  • 无法导入 langchain.agents.load_tools

    我正在尝试使用 LangChain Agents 但无法导入 load tools 版本 langchain 0 0 27 我尝试过这些 from langchain agents import initialize agent from
  • 嵌套作用域和 Lambda

    def funct x 4 action lambda n x n return action x funct print x 2 prints 16 我不太明白为什么2会自动分配给n n是返回的匿名函数的参数funct 完全等价的定义fu
  • Django 视图中的“请求”是什么

    在 Django 第一个应用程序的 Django 教程中 我们有 from django http import HttpResponse def index request return HttpResponse Hello world
  • 尽管我已在 python ctypes 中设置了信号处理程序,但并未调用它

    我尝试过使用 sigaction 和 ctypes 设置信号处理程序 我知道它可以与python中的信号模块一起使用 但我想尝试学习 当我向该进程发送 SIGTERM 时 但它没有调用我设置的处理程序 只打印 终止 为什么它不调用处理程序
  • Pandas 组合不同索引的数据帧

    我有两个数据框df 1 and df 2具有不同的索引和列 但是 有一些索引和列重叠 我创建了一个数据框df索引和列的并集 因此不存在重复的索引或列 我想填写数据框df通过以下方式 for x in df index for y in df
  • Django REST Framework - CurrentUserDefault 使用

    我正在尝试使用CurrentUserDefault一个序列化器的类 user serializers HiddenField default serializers CurrentUserDefault 文档说 为了使用它 请求 必须作为
  • Python GTK+ 画布

    我目前正在通过 PyGobject 学习 GTK 需要画布之类的东西 我已经搜索了文档 发现两个小部件似乎可以完成这项工作 GtkDrawingArea 和 GtkLayout 我需要一些基本函数 如 fillrect 或 drawline
  • 如果 PyPy 快 6.3 倍,为什么我不应该使用 PyPy 而不是 CPython?

    我已经听到很多关于PyPy http en wikipedia org wiki PyPy项目 他们声称它比现有技术快 6 3 倍CPython http en wikipedia org wiki CPython口译员开启他们的网站 ht
  • 制作一份 Python 文档的 PDF 文件

    Python 官方网站提供 PDF 文档下载 但它们是按章节分隔的 我下载了源代码并构建了 PDF 文档 这些文档也是单独的 PDF 我怎么能够从源代码中的 Makefile 构建一个 PDF 文件 我认为这样阅读起来会更方便 如果连接单独
  • 等待子进程使用 os.system

    我用了很多os system在 for 循环内调用创建后台进程 如何等待所有后台进程结束 os wait告诉我没有子进程 ps 我使用的是Solaris 这是我的代码 usr bin python import subprocess imp
  • 在virtualenv中下载sqlite3

    我正在尝试使用命令创建应用程序python3 manage py startapp webapp但我收到一条错误消息 django core exceptions ImproperlyConfigured 加载时出错 pysqlite2 或

随机推荐