栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何为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.


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/659734.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号