gpt4 book ai didi

Python点击: How to implement a help command that behaves like `--help` ?

转载 作者:行者123 更新时间:2023-12-03 08:58:29 27 4
gpt4 key购买 nike

我有一个 python click CLI。当我将 --help 传递给任何命令时,它会打印一条我喜欢的帮助消息。我发现现在很多用户都在输入

mycli help foo

而不是

mycli foo --help

有没有办法让前者像后者一样以通用方式对所有命令起作用?

该命令的实现大致如下

@click.group()
@click.pass_context
def cli(ctx):
ctx.obj = {}

@cli.command()
@click.argument('my_arg')
@click.pass_context
@report_errors
def foo(ctx, my_arg):
# some stuff here

最佳答案

click.Command 对象有一个 get_help()返回其 --help 字符串的方法。将此与该组的 get_command() 结合起来查找子命令的方法,类似这样的东西应该可以工作(未经测试):

@cli.command()
@click.argument('subcommand')
@click.pass_context
def help(ctx, subcommand):
subcommand_obj = cli.get_command(ctx, subcommand)
if subcommand_obj is None:
click.echo("I don't know that command.")
else:
click.echo(subcommand_obj.get_help(ctx))

关于Python点击: How to implement a help command that behaves like `--help` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53130784/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com