Python Click: custom error message

后端 未结 1 525
你的背包
你的背包 2021-01-12 03:17

I use the excellent Python Click library for handling command line options in my tool. Here\'s a simplified version of my code (full script here):

@click.com         


        
1条回答
  •  再見小時候
    2021-01-12 03:22

    Message construction for most errors in python-click is handled by the show method of the UsageError class: click.exceptions.UsageError.show.

    So, if you redefine this method, you will be able to create your own customized error message. Below is an example of a customization which appends the help menu to any error message which answers this SO question:

    def modify_usage_error(main_command):
        '''
            a method to append the help menu to an usage error
    
        :param main_command: top-level group or command object constructed by click wrapper 
        :return: None
        '''
    
        from click._compat import get_text_stderr
        from click.utils import echo
        def show(self, file=None):
            import sys
            if file is None:
                file = get_text_stderr()
            color = None
            if self.ctx is not None:
                color = self.ctx.color
                echo(self.ctx.get_usage() + '\n', file=file, color=color)
            echo('Error: %s\n' % self.format_message(), file=file, color=color)
            sys.argv = [sys.argv[0]]
            main_command()
    
        click.exceptions.UsageError.show = show
    

    Once you define your main command, you can then run the modifier script:

    import click
    @click.group()
    def cli():
        pass
    
    modify_usage_error(cli)
    

    I have not explored whether there are runtime invocations of ClickException other than usage errors. If there are, then you might need to modify your custom error handler to first check that ctx is an attribute before you add the line click.exceptions.ClickException.show = show since it does not appear that ClickException is fed ctx at initialization.

    0 讨论(0)
提交回复
热议问题