python click subcommand unified error handling

2024/9/23 1:34:02

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():passif __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.

Answer

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:

Code:

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)

Test Code:

import click@click.group(cls=CatchAllExceptions)
def cli():pass@cli.command()
def foo():raise Exception('an exception!')if __name__ == '__main__':cli('foo'.split())

Results:

We found an exception!
https://en.xdnf.cn/q/71882.html

Related Q&A

Data structure for large ranges of consecutive integers?

Suppose you have a large range of consecutive integers in memory, each of which belongs to exactly one category. Two operations must be O(log n): moving a range from one category to another, and findin…

polars slower than numpy?

I was thinking about using polars in place of numpy in a parsing problem where I turn a structured text file into a character table and operate on different columns. However, it seems that polars is ab…

namespace error lxml xpath python

I am transforming word documents to xml to compare them using the following code:word = win32com.client.Dispatch(Word.Application) wd = word.Documents.Open(inFile) # Converts the word infile to xml out…

lark grammar: How does the escaped string regex work?

The lark parser predefines some common terminals, including a string. It is defined as follows:_STRING_INNER: /.*?/ _STRING_ESC_INNER: _STRING_INNER /(?<!\\)(\\\\)*?/ ESCAPED_STRING : "\&quo…

Pycharm unresolved reference on join of os.path

After upgrade pycharm to 2018.1, and upgrade python to 3.6.5, pycharm reports "unresolved reference join". The last version of pycharm doesnt show any warning for the line below:from os.path …

Apply Border To Range Of Cells Using Openpyxl

I am using python 2.7.10 and openpyxl 2.3.2 and I am a Python newbie.I am attempting to apply a border to a specified range of cells in an Excel worksheet (e.g. C3:H10). My attempt below is failing wit…

Make a functional field editable in Openerp?

How to make functional field editable in Openerp?When we createcapname: fields.function(_convert_capital, string=Display Name, type=char, store=True ),This will be displayed has read-only and we cant …

how to read a fasta file in python?

Im trying to read a FASTA file and then find specific motif(string) and print out the sequence and number of times it occurs. A FASTA file is just series of sequences(strings) that starts with a header…

Passing a pandas dataframe column to an NLTK tokenizer

I have a pandas dataframe raw_df with 2 columns, ID and sentences. I need to convert each sentence to a string. The code below produces no errors and says datatype of rule is "object." raw_d…

SWIG - Wrap C string array to python list

I was wondering what is the correct way to wrap an array of strings in C to a Python list using SWIG.The array is inside a struct :typedef struct {char** my_array;char* some_string; }Foo;SWIG automati…