Python Click自定义HelpFormatter添加帮助输出多行前缀
自定义CLI工具的帮助信息前缀(基于Click框架)
需求说明
需要在CLI工具(如mytool --help)的帮助输出开头,默认的Usage: ...文本之前添加多行自定义前缀,预期输出示例:
This is mytool cli tool as part of tool-suite abc. Usage: mytool [OPTIONS] COMMAND [ARGS]... Options: --help Show this message and exit. Commands: version Display package version.
实现方案
通过自定义HelpFormatter类并重写相关方法,再将其绑定到Click的Group或Command上即可实现。以下是完整示例:
代码实现
import click from click.formatting import HelpFormatter class CustomHelpFormatter(HelpFormatter): def write_usage(self, prog, args="", prefix="Usage: "): # 先写入自定义前缀文本 self.write("This is mytool cli tool \nas part of tool-suite abc.\n\n") # 调用父类方法输出默认的Usage内容 super().write_usage(prog, args, prefix) @click.group(formatter_class=CustomHelpFormatter) def mytool(): pass @mytool.command() def version(): """Display package version.""" click.echo("v1.0.0") if __name__ == "__main__": mytool()
关键说明
- 自定义
CustomHelpFormatter继承自Click的HelpFormatter,重写write_usage方法,在父类逻辑执行前先写入自定义前缀文本 - 创建命令组(
mytool)时,通过formatter_class参数指定使用自定义格式化器 - 若为单个独立命令,同样可以在
@click.command()中传入formatter_class=CustomHelpFormatter来生效
测试效果
运行python your_script.py --help,即可得到符合预期的帮助输出。
内容的提问来源于stack exchange,提问作者c0dy01
相关产品推荐
相关产品推荐

