你可以写一个装饰者:
from functools import wraps def http_safe(func): @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except HTTPServiceError, e: click.echo('{[code]}: {[message]}'.format(e.details['errors'][0])) return wrapper
然后使用它:
@http_safe def cloudflare_add_zone(ctx, url, jumpstart, organization): if organization: ctx.create_zone(url, jumpstart, organization) else: ctx.create_zone(url, jumpstart) click.echo('Zone successfully created: %s' % url)