【问题标题】:How to set the default option as -h for Python click?如何将默认选项设置为 Python click 的 -h?
【发布时间】:2018-10-30 17:30:53
【问题描述】:

如何将默认选项设置为 -h 用于 Python 点击​​?

默认情况下,当duh.py 没有参数时,我的脚本不显示任何内容:

import click


CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])

@click.command(context_settings=CONTEXT_SETTINGS)
@click.option('--toduhornot', is_flag=True, help='prints "duh..."')
def duh(toduhornot):
    if toduhornot:
        click.echo('duh...')

if __name__ == '__main__':
    duh()

[出]:

$ python3 test_click.py -h
Usage: test_click.py [OPTIONS]

Options:
  --toduhornot  prints "duh..."
  -h, --help    Show this message and exit.



$ python3 test_click.py --toduhornot
duh...


$ python3 test_click.py 

问题:

如上图,默认不打印信息python3 test_click.py

有没有这样的方法,如果没有给出参数,默认选项设置为-h,例如

$ python3 test_click.py 
Usage: test_click.py [OPTIONS]

Options:
  --toduhornot  prints "duh..."
  -h, --help    Show this message and exit.

【问题讨论】:

  • 那么如果没有给出任何选项,那么你想默认帮助吗?你说:如果没有给出参数,但是你的例子只定义了一个选项,它没有定义任何参数。

标签: python command-line-interface argparse python-click


【解决方案1】:

对于version 7.1,可以简单地指定@click.command(no_args_is_help=True)

【讨论】:

    【解决方案2】:

    你的结构不是推荐的,你应该使用:

    import click
    
    
    CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
    
    
    @click.group(context_settings=CONTEXT_SETTINGS)
    def cli():
        pass
    
    
    @cli.command(help='prints "duh..."')
    def duh():
        click.echo('duh...')
    
    if __name__ == '__main__':
        cli()
    

    然后python test_click.py会打印帮助信息:

    Usage: test_click.py [OPTIONS] COMMAND [ARGS]...
    
    Options:
      -h, --help  Show this message and exit.
    
    Commands:
      duh  prints "duh..."
    

    所以您可以使用python test_click.py duh 调用duh

    更新

    import click
    
    
    CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
    
    @click.command(context_settings=CONTEXT_SETTINGS)
    @click.option('--toduhornot', is_flag=True, help='prints "duh..."')
    def duh(toduhornot):
        if toduhornot:
            click.echo('duh...')
        else:
            with click.Context(duh) as ctx:
                click.echo(ctx.get_help())
    
    if __name__ == '__main__':
        duh()
    

    【讨论】:

    • 嗯,但这会强制执行duh 命令,当我执行python test_click.py duh 时,它仍然不会打印出帮助消息=(
    • 我也可以检查一下if *args == None吗?
    【解决方案3】:

    如果您从 click.Command 继承并覆盖 parse_args() 方法,则可以创建一个自定义类以默认提供帮助:

    自定义类

    import click
    
    class 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() 装饰器,例如:

    @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.7
    Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
    -----------
    > --toduhornot
    duh...
    -----------
    > 
    Usage: test.py [OPTIONS]
    
    Options:
      --toduhornot  prints "duh..."
      -h, --help    Show this message and exit.
    -----------
    > --help
    Usage: test.py [OPTIONS]
    
    Options:
      --toduhornot  prints "duh..."
      -h, --help    Show this message and exit.
    -----------
    > -h
    Usage: test.py [OPTIONS]
    
    Options:
      --toduhornot  prints "duh..."
      -h, --help    Show this message and exit.
    

    【讨论】:

      【解决方案4】:

      我发现的最简单的方法

      import click
      
      @click.command()
      @click.option('--option')
      @click.pass_context
      
      def run(ctx, option):
          if not option:
              click.echo(ctx.get_help())
              ctx.exit()
      

      【讨论】:

      • 完美!正是我想要的。其他一切都非常复杂。
      猜你喜欢
      • 1970-01-01
      • 2012-11-16
      • 1970-01-01
      • 1970-01-01
      • 2014-11-27
      • 2016-10-01
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多