在 Python 中单击如何查看其父项具有所需选项的子命令的 --help?

In Python Click how do I see --help for Subcommands whose parents have required options?

我遇到了与 中描述的问题类似的问题,但是我在命令之前需要选项而不是参数。我已尝试根据我的情况调整已接受的答案,但无法使其正常工作,例如

#! python3

import click

    class PerCommandOptWantSubCmdHelp(click.Option):

    def handle_parse_result(self, ctx, opts, args):
        # check to see if there is a --help on the command line
        if any(arg in ctx.help_option_names for arg in args):

            # if asking for help see if we are a subcommand name
            for arg in opts.values():
                if arg in ctx.command.commands:

                    # this matches a sub command name, and --help is
                    # present, let's assume the user wants help for the
                    # subcommand
                    args = [arg] + args

        return super(PerCommandOptWantSubCmdHelp, self).handle_parse_result(ctx, opts, args)



@click.group()
def foo():
    pass

@click.group('map')
@click.option('-f', '--force', is_flag=True)
@click.option('-i', '--id')
@click.option('-b', '--base', required=True, cls=PerCommandOptWantSubCmdHelp)
def archive_map(force, id, base):
    click.echo('Map called')

volla.add_command(archive_map)


@click.command('bar')
@click.option('-t', '--template', required=True)
@click.option('-p', '--project', required=True)
def bar_command():
    pass

archive_map.add_command(bar_command);


if __name__ == '__main__':
    foo()

但我仍然有这种行为

$ ./foo map bar --help
Usage: foo map [OPTIONS] COMMAND [ARGS]...
Try 'foo map --help' for help.

Error: Missing option '-b' / '--base'.
$

对我的误解有什么想法吗?

我做过这样的事情:

class PerCommandOptWantSubCmdHelp(click.Option):

    def handle_parse_result(self, ctx, opts, args):
        # check to see if there is a --help on the command line
        if any(arg in ctx.help_option_names for arg in args):
            # if asking for help see if we are a subcommand name
            remaining_args = [arg for arg in args if arg not in ctx.help_option_names]
            for arg in remaining_args:

                if arg in ctx.command.commands:
                    click.echo(ctx.command.get_help(ctx))
                    click.echo()
                    click.echo(f'Command {arg} usage')
                    click.echo(ctx.command.commands[arg].get_help(ctx))

        return super(PerCommandOptWantSubCmdHelp, self).handle_parse_result(ctx, opts, args)

本质上,如果您调用了带帮助的子命令,获取父级的帮助消息,输出它,然后输出您当前子命令的帮助消息。

您的输出将如下所示:

Usage: main.py map [OPTIONS] COMMAND [ARGS]...

Options:
  -f, --force
  -i, --id TEXT
  -b, --base TEXT  [required]
  --help           Show this message and exit.

Commands:
  bar

Command bar usage:
Usage: main.py map [OPTIONS]

Options:
  -t, --template TEXT  [required]
  -p, --project TEXT   [required]
  --help               Show this message and exit.
Usage: main.py map [OPTIONS] COMMAND [ARGS]...
Try 'main.py map --help' for help.

Error: Missing option '-b' / '--base'.

这有帮助吗?