如何为Python click设置默认选项为-h? [英] How to set the default option as -h for Python click?
问题描述
默认情况下,当没有为duh.py
提供参数时,我的脚本不显示任何内容:
By default, my script, shows nothing when no arguments is given to the 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()
[out]:
$ 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
,如果没有给出任何参数,例如
Is there a way such that, the default option is set to -h
if no arguments is given, e.g.
$ python3 test_click.py
Usage: test_click.py [OPTIONS]
Options:
--toduhornot prints "duh..."
-h, --help Show this message and exit.
推荐答案
如果从click.Command
继承并覆盖parse_args()
方法,则可以创建一个默认的自定义类来提供帮助,例如:
If you inherit from click.Command
and override the parse_args()
method, you can create a custom class to default to help like:
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()
装饰器,如下所示:
Using Custom Class:
To use the custom class, pass the cls
parameter to @click.command()
decorator like:
@click.command(cls=DefaultHelp)
这是如何工作的?
之所以有用,是因为click是一个设计良好的OO框架. @click.command()
装饰器通常实例化一个
click.Command
对象,但允许使用cls
参数覆盖此行为.所以这是一个相对
很容易从我们自己的类中的click.Command
继承下来,并超越所需的方法.
How does this work?
This works because click is a well designed OO framework. The @click.command()
decorator usually instantiates a
click.Command
object but allows this behavior to be over ridden with the cls
parameter. So it is a relatively
easy matter to inherit from click.Command
in our own class and over ride the desired methods.
在这种情况下,我们重写click.Command.parse_args()
并检查是否有空的参数列表.如果为空,则调用帮助.此外,如果未另外设置,则此类会将帮助默认为['-h', '--help']
.
In this case we over-ride click.Command.parse_args()
and check for an empty argument list. If it is empty then we invoke the help. In addition this class will default the help to ['-h', '--help']
if it is not otherwise set.
@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.
这篇关于如何为Python click设置默认选项为-h?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!