点击。通过覆盖UsageError的显示功能,自定义 "缺失参数 "的错误处理。

问题描述 投票:1回答:1

我目前正在尝试自定义错误处理,当一个命令在没有提供所需参数的情况下被发出时,使用Click。这个问题 这可以通过覆盖 show 的功能 click.exceptions.UsageError. 然而,我试着修改那里提供的解决方案,但我不能让它工作,在我的例子中,我希望能够得到应该执行的命令(但由于缺少参数而失败),并根据输入的命令,我想进一步处理。

在我的例子中,我希望能够得到应该执行的命令(但由于缺少参数而失败),并且根据输入的命令,我想进一步处理。

@click.group(cls=MyGroup)
def myapp():
    pass

@myapp.command()
@click.argument('myarg',type=str)
def mycommand(myarg: str) -> None:
    do_stuff(myarg)

如果命令是这样的 myapp mycommand 我找了一会儿,但我无法找出如何获取命令(我试过传递上下文,但就我读到的。UsageError 在初始化时没有得到上下文的传递)。)

如果有任何提示或想法,我将感激不尽。

EDIT: 实现了 myGroup 看起来像这样。

class myGroup(click.Group):
"""
Customize help order and get_command
https://stackoverflow.com/a/47984810/713980
"""

def __init__(self, *args, **kwargs):
    self.help_priorities = {}
    super(myGroup, self).__init__(*args, **kwargs)

def get_help(self, ctx):
    self.list_commands = self.list_commands_for_help
    return super(myGroup, self).get_help(ctx)

def list_commands_for_help(self, ctx):
    """reorder the list of commands when listing the help"""
    commands = super(myGroup, self).list_commands(ctx)
    return (c[1] for c in sorted((self.help_priorities.get(command, 1000), command) for command in commands))

def command(self, *args, **kwargs):
    """Behaves the same as `click.Group.command()` except capture
    a priority for listing command names in help.
    """
    help_priority = kwargs.pop('help_priority', 1000)
    help_priorities = self.help_priorities

    def decorator(f):
        cmd = super(myGroup, self).command(*args, **kwargs)(f)
        help_priorities[cmd.name] = help_priority
        return cmd
    return decorator

def get_command(self, ctx, cmd_name):
    rv = click.Group.get_command(self, ctx, cmd_name)
    if rv is not None:
        return rv
    sim_commands = most_sim_com(cmd_name, COMMANDS)

    matches = [cmd for cmd in self.list_commands(ctx) if cmd in sim_commands]
    if not matches:
        ctx.fail(click.style('Unknown command and no similar command was found!', fg='red'))
    elif len(matches) == 1:
        click.echo(click.style(f'Unknown command! Will use best match {matches[0]}.', fg='red'))
        return click.Group.get_command(self, ctx, matches[0])
    ctx.fail(click.style(f'Unknown command. Most similar commands were {", ".join(sorted(matches))}', fg='red'))
python command-line-interface command-line-arguments python-click
1个回答
1
投票

这是一个初稿,也是我能想到的最天真的解决方案,所以如果不能完全解决你的问题,可能会改变它。把你的代码改成这样会有帮助吗?

@click.group(cls=MyGroup)
def myapp():
    pass

@myapp.command()
@click.argument('myarg',type=str, required=False)
def mycommand(myarg: str=None) -> None:
    validate_my_command(myarg) # this is where you do your custom logic and error message handling

这样做的好处是,它是显式的,并且符合 Click的建议方法。然而,如果你想对每条命令都这样做,我们可以考虑更复杂的方法。

让我知道你的想法

© www.soinside.com 2019 - 2024. All rights reserved.