我的问题是:
假设我使用Python Click
构建了一个CLI,并为其创建了组和命令的自定义类,这些类包装调用以捕获异常:
logger = logging.getLogger()
class CLICommandInvoker(click.Command):
def invoke(self, ctx):
command = ctx.command.name
try:
logger.info("Running {command} command".format(command=command))
ret = super(CLICommandInvoker, self).invoke(ctx)
logger.info("Completed {command} command".format(command=command))
return ret
except Exception as exc:
logger.error(
'Command {command} failed with exception: {exc}'.format(command=command, exc=exc)
)
""" In case command invoked from another command """
raise Exception("Failed to invoke {command} command".format(command=command))
class CLIGroupInvoker(click.Group):
def invoke(self, ctx):
group = ctx.command.name
try:
ret = super(CLIGroupInvoker, self).invoke(ctx)
group_subcommand = ctx.invoked_subcommand
logger.info(
'Command "{group}-{subcommand}" completed successfully'.format(group = group, subcommand = group_subcommand)
)
return ret
except Exception:
group_subcommand = ctx.invoked_subcommand
logger.error(
'Command "{group}-{subcommand}" failed'.format(group=group, subcommand=group_subcommand)
)
例如,我在一个组中有两个命令:
^{pr2}$因此,代码运行良好,但是c2
中上下文的invoke
方法没有在我的CLICommandInvoker
中运行自定义调用,而是直接转到c1
函数。我看不到Running c1 command
或自定义invoke
中关于c1
的日志,只有关于c2
的日志。在
那么,我做错什么了?从另一个命令调用命令时,如何让命令调用使用自定义类?还是不可能?在
我知道有一种解决方案可以简单地重构代码以提取实现本身,并简单地让命令“包装”实际的逻辑,但我们假设目前还不可能。在
您遇到的问题是,您正在调用
click.Context.invoke
,它不使用click.Command.invoke
。使用一个小的DRY我们可以将您的调用包装器分解出来,然后使用它,如下所示:代码:
调用代码:
包装器可以直接调用,如下所示:
^{pr2}$或者可以在继承类中使用,例如:
测试代码:
结果:
相关问题 更多 >
编程相关推荐