我有一个与描述的in this question类似的问题,但是我需要在命令之前使用选项,而不是参数。例如,我试着根据我的情况调整公认的答案,但无法使其起作用
#! 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'.
$对我误解的地方有什么想法吗?
发布于 2020-04-29 20:43:09
我做过这样的事情:
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)从本质上讲,如果您已经使用help调用子命令,则获取父命令的帮助消息,输出它,然后输出当前子命令的帮助消息。
输出将如下所示:
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'.这有帮助吗?
https://stackoverflow.com/questions/61474544
复制相似问题