如何为Python click设置默认选项为-h?

如何为Python click设置默认选项为-h?,第1张

如何为Python click设置默认选项为-h?

如果您继承

click.Command
并覆盖该
parse_args()
方法,则可以创建一个默认的自定义类来提供帮助,例如:

自定义类
import clickclass DefaultHelp(click.Command):    def __init__(self, *args, **kwargs):        context_settings = kwargs.setdefault('context_settings', {})        if 'help_option_names' not in context_settings: context_settings['help_option_names'] = ['-h', '--help']        self.help_flag = context_settings['help_option_names'][0]        super(DefaultHelp, self).__init__(*args, **kwargs)    def parse_args(self, ctx, args):        if not args: args = [self.help_flag]        return super(DefaultHelp, self).parse_args(ctx, args)
使用自定义类:

要使用自定义类,请将

cls
参数传递给
@click.command()
decorator,如下所示:

@click.command(cls=DefaultHelp)
这是如何运作的?

之所以可行,是因为click是一个设计良好的OO框架。该

@click.command()
装饰通常实例化一个
click.Command
对象,但允许与被骑过这种行为
cls
的参数。因此,
click.Command
在我们自己的类中继承并超越所需的方法是相对容易的事情。

在这种情况下,我们将改写

click.Command.parse_args()
并检查空的参数列表。如果为空,则调用帮助。另外,
['-h', '--help']
如果没有另外设置,此类将默认帮助。

测试代码:
@click.command(cls=DefaultHelp)@click.option('--toduhornot', is_flag=True, help='prints "duh..."')def duh(toduhornot):    if toduhornot:        click.echo('duh...')if __name__ == "__main__":    commands = (        '--toduhornot',        '',        '--help',        '-h',    )    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) duh(cmd.split())        except baseException as exc: if str(exc) != '0' and          not isinstance(exc, (click.ClickException, SystemExit)):     raise
结果:
Click Version: 6.7Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]-----------> --toduhornotduh...-----------> Usage: test.py [OPTIONS]Options:  --toduhornot  prints "duh..."  -h, --help    Show this message and exit.-----------> --helpUsage: test.py [OPTIONS]Options:  --toduhornot  prints "duh..."  -h, --help    Show this message and exit.-----------> -hUsage: test.py [OPTIONS]Options:  --toduhornot  prints "duh..."  -h, --help    Show this message and exit.


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5661801.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存