alv*_*vas 6 python command-line-interface argparse python-click
默认情况下,我的脚本在没有提供参数时不显示任何内容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()
Run Code Online (Sandbox Code Playgroud)
$ 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
Run Code Online (Sandbox Code Playgroud)
如上图,默认不打印信息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.
Run Code Online (Sandbox Code Playgroud)
如果您继承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)
Run Code Online (Sandbox Code Playgroud)
要使用自定义类,请将cls参数传递给@click.command()装饰器,如下所示:
@click.command(cls=DefaultHelp)
Run Code Online (Sandbox Code Playgroud)
这是可行的,因为 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
Run Code Online (Sandbox Code Playgroud)
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.
Run Code Online (Sandbox Code Playgroud)
您的结构不是推荐的结构,您应该使用:
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()
Run Code Online (Sandbox Code Playgroud)
然后python test_click.py将打印帮助信息:
Usage: test_click.py [OPTIONS] COMMAND [ARGS]...
Options:
-h, --help Show this message and exit.
Commands:
duh prints "duh..."
Run Code Online (Sandbox Code Playgroud)
所以你可以使用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()
Run Code Online (Sandbox Code Playgroud)