python - 在 Python Click 中对帮助输出进行分类
问题描述
我试图弄清楚如何对 Click 中的命令进行分类,使其类似于以kubectl
分离命令的方式使用的结构。
例如,在普通的 Click 帮助输出中,我们有:
Usage: cli.py [OPTIONS] COMMAND [ARGS]...
A CLI tool
Options:
-h, --help Show this message and exit.
Commands:
command1 This is command1
command2 This is command2
command3 This is command3
command4 This is command4
相反,对我来说最理想的做法是进行分离以更好地对命令结构进行分类。
例如:
Usage: cli.py [OPTIONS] COMMAND [ARGS]...
A CLI tool
Options:
-h, --help Show this message and exit.
Specific Commands for X:
command1 This is command1
command2 This is command2
Specific Commands for Y:
command3 This is command3
command4 This is command4
Global Commands:
version Shows version
我也在为此使用最新的 Python 和最新版本的 Click。
我曾尝试研究挂钩到各种 Click 类以改变这种行为,但没有成功。我得到的最接近的是能够根据优先级构造命令,但我无法像上面的示例那样在逻辑上将它们分开。
任何帮助将不胜感激。
解决方案
我通过创建自己的方法实现了这一点click.Group
:
class OrderedGroup(click.Group):
def __init__(self, name=None, commands=None, **attrs):
super(OrderedGroup, self).__init__(name, commands, **attrs)
self.commands = commands or collections.OrderedDict()
def list_commands(self, ctx):
return self.commands
def format_commands(self, ctx, formatter):
super().get_usage(ctx)
formatter.write_paragraph()
with formatter.section("Specific Commands for X:"):
formatter.write_text(
f'{self.commands.get("command1").name}\t\t{self.commands.get("command1").get_short_help_str()}')
formatter.write_text(
f"{self.commands.get('command2').name}\t\t{self.commands.get('command2').get_short_help_str()}")
with formatter.section("Specific Commands for Y:"):
formatter.write_text(
f'{self.commands.get("command3").name}\t\t{self.commands.get("command3").get_short_help_str()}')
formatter.write_text(
f'{self.commands.get("command4").name}\t\t{self.commands.get("command4").get_short_help_str()}')
with formatter.section("Global Commands"):
formatter.write_text(
f'{self.commands.get("version").name}\t\t{self.commands.get("version").get_short_help_str()}')
并创建了cli
这样的组:
@click.group(cls=OrderedGroup)
def cli():
pass
这有帮助吗?
推荐阅读
- maven - 如何获取maven项目dependencyManagement块中列出的pom(bom)的artifactId
- r - 使用 R 向 Leaflet 中的图层控制框添加标题
- android - 在 playStore 上提交被拒绝的应用程序
- android - Kotlin:滚动时隐藏/显示 BottomNavigationView
- javascript - Refreshing page with background video
- javascript - 是否可以进行双重替换?
- sql - 通过 SQL 删除 Wordpress 中所有未使用的类别
- mysql - 如何将 10 位数字存储到 sql bigint 数据类型中?
- node.js - 仅限移动设备 CORS 错误:Node.js 中的 Access-Control-Allow-Origin 不允许来源
- c# - 如何向文字对象添加方法和字段?