我将此代码段用于我的自定义组(来自here),以允许使用前缀
class AliasedGroup(click.Group):
def get_command(self, ctx, cmd_name):
rv = click.Group.get_command(self, ctx, cmd_name)
if rv is not None:
return rv
matches = [x for x in self.list_commands(ctx)
if x.startswith(cmd_name)]
if not matches:
return None
elif len(matches) == 1:
return click.Group.get_command(self, ctx, matches[0])
ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))
但是,使用情况输出变得非常愚蠢:它显示命令的前缀,而不是完全显示它们:
Usage: test_core a c [OPTIONS]
我想看看
Usage: test_core add combined [OPTIONS]
甚至当我调用test_core a c -h
时
我已经调查过了,但似乎没有明显的解决办法。格式化程序逻辑不知道它们的原始名称。也许可以重写MultiCommand.resolve_command
来处理MultiCommand/Group.get_command
的重写版本,该版本也返回原始命令名。但这可能会破坏一些东西,也许有更简单的方法
完整代码:
import click
class AliasedGroup(click.Group):
def get_command(self, ctx, cmd_name):
rv = click.Group.get_command(self, ctx, cmd_name)
if rv is not None:
return rv
matches = [x for x in self.list_commands(ctx)
if x.startswith(cmd_name)]
if not matches:
return None
elif len(matches) == 1:
return click.Group.get_command(self, ctx, matches[0])
ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))
@click.group(cls=AliasedGroup, context_settings={'help_option_names': ['-h', '--help']})
def cli():
pass
@cli.group(cls=AliasedGroup)
def add():
pass
@add.command()
@click.option('--yarr')
def combined():
pass
cli(['a', 'c', '-h'], prog_name='test_core')
您需要跟踪使用的别名
别名保存在全局变量中,因为
click
使用了大量上下文实例您需要实现自己的HelpFormatter。这涵盖了帮助构造的所有用途
在
write_usage
中,用完整的命令名替换别名。作为test_core add auto -h
的命令,跟踪填充的别名以覆盖test_core a a -h
的情况。如果在prog
中找不到别名,请不要尝试使用下一个别名(while
而不是for
)终端输出
相关问题 更多 >
编程相关推荐