如何为Python click设置默认选项为-h?
问题内容:
如何为Python click设置默认选项为-h?
默认情况下,当没有为参数提供参数时,我的脚本不显示任何内容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.
问题答案:
如果您继承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()
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.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.