python click子命令统一错误处理 [英] python click subcommand unified error handling
问题描述
在有命令组并且每个子命令都可能引发异常的情况下,如何在一个地方一起处理它们?
In the case where there are command groups and every sub-command may raise exceptions, how can I handle them all together in one place?
给出以下示例:
import click
@click.group()
def cli():
pass
@cli.command()
def foo():
pass
if __name__ == '__main__':
cli()
cli
和foo
都可能升高.我知道一种可能的解决方案是将try-except
放在if
子句中的cli()
周围.但这在分发软件包时不起作用.在 setup.py 中,您必须指定一个入口点(在本例中为cli
). if
子句将不会执行.
Both cli
and foo
may raise. I know that one possible solution is to place try-except
around cli()
in the if
clause. But that does not work when you distribute a package. In setup.py, you have to specify an entry point (in this case, cli
). The if
clause will not be executed.
推荐答案
您可以通过继承自定义click.Group
来创建自定义click.Group
.通过将自定义组作为cls
参数传递给click.group()
装饰器,可以使用该自定义组.如果覆盖__call__
方法,则可以插入类似以下内容的异常处理程序:
You can create a custom click.Group
by inheriting from same. The custom group can be used by passing it as the cls
parameter to the click.group()
decorator. If you override the __call__
method, you can insert an exception handler like:
class CatchAllExceptions(click.Group):
def __call__(self, *args, **kwargs):
try:
return self.main(*args, **kwargs)
except Exception as exc:
click.echo('We found %s' % exc)
测试代码:
import click
@click.group(cls=CatchAllExceptions)
def cli():
pass
@cli.command()
def foo():
raise Exception('an exception!')
if __name__ == '__main__':
cli('foo'.split())
结果:
We found an exception!
这篇关于python click子命令统一错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!