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?
Given the example below:
import click
@click.group()
def cli():
pass
@cli.command()
def foo():
pass
if __name__ == '__main__':
cli()
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.
You can create a custom
click.Group
by inheriting from same. The custom group can be used by passing it as thecls
parameter to theclick.group()
decorator. If you override the__call__
method, you can insert an exception handler like:Code:
Test Code:
Results: