如何在Python click模块生成的使用消息的末尾添加多个空行?

2024-10-03 15:26:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题与this SO Q&A有点相似,但是我想在click生成的输出结尾处添加额外的空行。在

我有以下代码:

EPILOG='\n' + '-' * 20

 class SpecialEpilog(click.Group):
     def format_epilog(self, ctx, formatter):
         if self.epilog:
             formatter.write_paragraph()
             for line in self.epilog.split('\n'):
                 formatter.write_text(line)

 #------------------
 @click.group(cls=SpecialEpilog, epilog=EPILOG, invoke_without_command=True)
 def cli():
     """Wraps cloud.tenable.com Nessus API calls in useful ways

     \b
     The CLI provides access to these subcommands:
         - agent
         - os
         - vuln

     Each subcommand can perform useful API queries within their respective domain.
     """
     pass

 #------------------
 # main
 cli.add_command(os)
 cli.add_command(agent)
 cli.add_command(vuln)

这将产生以下用法输出:

^{2}$

我的问题:

我想不出一个不需要可打印字符的方法。如果删除上面的短划线序列,换行符(\n)将不再显示。换句话说,上面的用法是这样的:

...
Commands:
  agent  API calls focusing on assets' details - Works...
  os     API calls focusing on operating systems -...
  vuln   API calls focusing on vulnerabilities - Works...
$ myprompt>

Tags: selfaddapicliosonformattercommand
1条回答
网友
1楼 · 发布于 2024-10-03 15:26:57

问题是click进行了优化以删除帮助末尾的任何空行。该行为在click.Command.get_help()中,可以如下方式重写:

代码:

class SpecialEpilog(click.Group):

    def get_help(self, ctx):
        """ standard get help, but without rstrip """
        formatter = ctx.make_formatter()
        self.format_help(ctx, formatter)
        return formatter.getvalue()

测试代码:

^{pr2}$

但我需要的是空白,不是尾声:

如果您只需要一些空行,那么我们可以完全忽略epilog,只需修改get_help()来添加相同的内容:

class AddSomeBlanksToHelp(click.Group):

    def get_help(self, ctx):
        return super(AddSomeBlanksToHelp, self).get_help(ctx) + '\n\n'

@click.group(cls=AddSomeBlanksToHelp, invoke_without_command=True)

相关问题 更多 >