Python 单击:设置工具下的异常处理



我有一个 python 点击应用程序,效果很好,但我希望在用户输入未知命令时收到通知。例如,如果mycli foo有效,但他们输入mycli bar,我想覆盖默认的异常处理行为并向错误跟踪器(例如滚动条(触发错误。

我找到了这个页面,它描述了如何覆盖异常处理,但它假设我有一个Command。我遇到的问题是,我还按照本指南与设置工具集成,它指向我在[console_scripts]部分中Command。例如,yourscript=yourscript:cli指向cli命令。

我不知道如何从[console_scripts]内部称呼cli.main(),或者这是否是正确的思考方式。

使用自定义click.Command类,可以捕获调用命令行,然后使用自定义类在异常处理程序的命令行中报告任何错误,如下所示:

自定义类

def CatchAllExceptions(cls, handler):
class Cls(cls):
_original_args = None
def make_context(self, info_name, args, parent=None, **extra):
# grab the original command line arguments
self._original_args = ' '.join(args)
try:
return super(Cls, self).make_context(
info_name, args, parent=parent, **extra)
except Exception as exc:
# call the handler
handler(self, info_name, exc)
# let the user see the original error
raise
def invoke(self, ctx):
try:
return super(Cls, self).invoke(ctx)
except Exception as exc:
# call the handler
handler(self, ctx.info_name, exc)
# let the user see the original error
raise
return Cls

def handle_exception(cmd, info_name, exc):
# send error info to rollbar, etc, here
click.echo(':: Command line: {} {}'.format(info_name, cmd._original_args))
click.echo(':: Raised error: {}'.format(exc))

使用自定义类

然后,要使用自定义命令/组,请将其作为cls参数传递给click.commandclick.group装饰器,例如:

@click.command(cls=CatchAllExceptions(click.Command, handler=report_exception))
@click.group(cls=CatchAllExceptions(click.Group, handler=report_exception))
@click.group(cls=CatchAllExceptions(click.MultiCommand, handler=report_exception))

请注意,需要指定需要哪个click.Command子类以及 要将异常信息发送到的处理程序。

这是如何工作的?

这是有效的,因为单击是一个设计良好的OO框架。@click.group()@click.command()修饰器通常实例化click.Groupclick.Command对象,但允许使用cls参数覆盖此行为。因此,从我们自己的类中的click.Command(等(继承并覆盖所需的方法相对容易。

在这种情况下,我们覆盖click.Command.make_context()以获取原始命令行,click.Command.invoke()捕获异常,然后调用异常处理程序。

测试代码:

import click
@click.group(cls=CatchAllExceptions(click.Group, handler=report_exception))
def cli():
"""A wonderful test program"""
pass
@cli.command()
def foo():
"""A fooey command"""
click.echo('Foo!')

if __name__ == "__main__":
commands = (
'foo',
'foo --unknown',
'foo still unknown',
'',
'--help',
'foo --help',
)
import sys, time
time.sleep(1)
print('Click Version: {}'.format(click.__version__))
print('Python Version: {}'.format(sys.version))
for cmd in commands:
try:
time.sleep(0.1)
print('-----------')
print('> ' + cmd)
time.sleep(0.1)
cli(cmd.split())
except BaseException as exc:
if str(exc) != '0' and 
not isinstance(exc, (click.ClickException, SystemExit)):
raise

结果:

Click Version: 6.7
Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
-----------
> foo
Foo!
-----------
> foo --unknown
Error: no such option: --unknown
:: Command line: test.py foo --unknown
:: Raised error: no such option: --unknown
-----------
> foo still unknown
:: Command line: test.py foo still unknown
:: Raised error: Got unexpected extra arguments (still unknown)
Usage: test.py foo [OPTIONS]
Error: Got unexpected extra arguments (still unknown)
-----------
> 
Usage: test.py [OPTIONS] COMMAND [ARGS]...
A wonderful test program
Options:
--help  Show this message and exit.
Commands:
foo  A fooey command
-----------
> --help
Usage: test.py [OPTIONS] COMMAND [ARGS]...
A wonderful test program
Options:
--help  Show this message and exit.
Commands:
foo  A fooey command
-----------
> foo --help
Usage: test.py foo [OPTIONS]
A fooey command
Options:
--help  Show this message and exit.

最新更新