Python 点击应用所需参数优先于子命令帮助选项
Python click application required parameters have precedence over sub command help option
我正在构建一个 click 7.x application with Python 3.6,但在获取帮助以处理子命令时遇到了一些问题。我有一个必需的全局选项,当我 运行 帮助任何子命令时,此选项被报告为丢失。
例如,给定以下虚拟脚本 cli.py
:
import click
@click.group()
@click.option('--directory', required=True)
def cli(directory):
"""
this is a tool that has an add and remove command
"""
click.echo(directory)
@cli.command()
@click.overwrite('--overwrite', is_flag=True)
def add(overwrite):
"""
this is the add command
"""
click.echo("add overwrite={}".format(overwrite))
@cli.command()
def remove():
"""
this is the remove command
"""
click.echo('remove')
if __name__ == '__main__':
cli()
当我运行以下内容时:
python cli.py --help
我得到了想要的输出:
Usage cli.py [OPTIONS] COMMAND [ARGS]...
this is a tool that has an add and remove command
Options:
--directory TEXT [required]
--help Show this message and exit.
Commands:
add this is the add command
remove this is the remove command
但是如果我运行这个:
python cli.py add --help
我收到以下错误:
Usage cli.py [OPTIONS] COMMAND [ARGS]...
Try "cli.py --help" for help.
Error: Missing option "--directory"
如何在不提供 --directory
选项的情况下获得显示 add 命令的帮助?
您可以使用自定义 click.Group
class 在请求 --help
时忽略所需的参数,例如:
自定义 Class:
class IgnoreRequiredWithHelp(click.Group):
def parse_args(self, ctx, args):
try:
return super(IgnoreRequiredWithHelp, self).parse_args(ctx, args)
except click.MissingParameter as exc:
if '--help' not in args:
raise
# remove the required params so that help can display
for param in self.params:
param.required = False
return super(IgnoreRequiredWithHelp, self).parse_args(ctx, args)
使用自定义 Class:
要使用自定义 class,请将其作为 cls
参数传递给组装饰器,例如:
@click.group(cls=IgnoreRequiredWithHelp)
....
def my_group():
....
这是如何工作的?
之所以可行,是因为 click 是一个设计良好的 OO 框架。 @click.group()
装饰器通常实例化一个 click.Group
对象,但允许使用 cls
参数覆盖此行为。因此,在我们自己的 class 中继承 click.Group
并覆盖所需的方法是一件相对容易的事情。
在这种情况下,我们超越 click.Group.parse_args()
并捕获 click.MissingParameter
异常。然后我们从所有参数中否定 required
属性,并重试解析。
测试代码:
import click
@click.group(cls=IgnoreRequiredWithHelp)
@click.option('--directory', required=True)
def cli(directory):
"""
this is a tool that has an add and remove command
"""
click.echo(directory)
@cli.command()
@click.option('--overwrite', is_flag=True)
def add(overwrite):
"""
this is the add command
"""
click.echo("add overwrite={}".format(overwrite))
@cli.command()
def remove():
"""
this is the remove command
"""
click.echo('remove')
if __name__ == "__main__":
commands = (
'add --help',
'--help',
'--directory a_dir add'
'',
)
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)
cli(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)]
-----------
> add --help
Usage: test.py add [OPTIONS]
this is the add command
Options:
--overwrite
--help Show this message and exit.
-----------
> --help
Usage: test.py [OPTIONS] COMMAND [ARGS]...
this is a tool that has an add and remove command
Options:
--directory TEXT
--help Show this message and exit.
Commands:
add this is the add command
remove this is the remove command
-----------
> --directory a_dir add
a_dir
add overwrite=False
我正在构建一个 click 7.x application with Python 3.6,但在获取帮助以处理子命令时遇到了一些问题。我有一个必需的全局选项,当我 运行 帮助任何子命令时,此选项被报告为丢失。
例如,给定以下虚拟脚本 cli.py
:
import click
@click.group()
@click.option('--directory', required=True)
def cli(directory):
"""
this is a tool that has an add and remove command
"""
click.echo(directory)
@cli.command()
@click.overwrite('--overwrite', is_flag=True)
def add(overwrite):
"""
this is the add command
"""
click.echo("add overwrite={}".format(overwrite))
@cli.command()
def remove():
"""
this is the remove command
"""
click.echo('remove')
if __name__ == '__main__':
cli()
当我运行以下内容时:
python cli.py --help
我得到了想要的输出:
Usage cli.py [OPTIONS] COMMAND [ARGS]...
this is a tool that has an add and remove command
Options:
--directory TEXT [required]
--help Show this message and exit.
Commands:
add this is the add command
remove this is the remove command
但是如果我运行这个:
python cli.py add --help
我收到以下错误:
Usage cli.py [OPTIONS] COMMAND [ARGS]...
Try "cli.py --help" for help.
Error: Missing option "--directory"
如何在不提供 --directory
选项的情况下获得显示 add 命令的帮助?
您可以使用自定义 click.Group
class 在请求 --help
时忽略所需的参数,例如:
自定义 Class:
class IgnoreRequiredWithHelp(click.Group):
def parse_args(self, ctx, args):
try:
return super(IgnoreRequiredWithHelp, self).parse_args(ctx, args)
except click.MissingParameter as exc:
if '--help' not in args:
raise
# remove the required params so that help can display
for param in self.params:
param.required = False
return super(IgnoreRequiredWithHelp, self).parse_args(ctx, args)
使用自定义 Class:
要使用自定义 class,请将其作为 cls
参数传递给组装饰器,例如:
@click.group(cls=IgnoreRequiredWithHelp)
....
def my_group():
....
这是如何工作的?
之所以可行,是因为 click 是一个设计良好的 OO 框架。 @click.group()
装饰器通常实例化一个 click.Group
对象,但允许使用 cls
参数覆盖此行为。因此,在我们自己的 class 中继承 click.Group
并覆盖所需的方法是一件相对容易的事情。
在这种情况下,我们超越 click.Group.parse_args()
并捕获 click.MissingParameter
异常。然后我们从所有参数中否定 required
属性,并重试解析。
测试代码:
import click
@click.group(cls=IgnoreRequiredWithHelp)
@click.option('--directory', required=True)
def cli(directory):
"""
this is a tool that has an add and remove command
"""
click.echo(directory)
@cli.command()
@click.option('--overwrite', is_flag=True)
def add(overwrite):
"""
this is the add command
"""
click.echo("add overwrite={}".format(overwrite))
@cli.command()
def remove():
"""
this is the remove command
"""
click.echo('remove')
if __name__ == "__main__":
commands = (
'add --help',
'--help',
'--directory a_dir add'
'',
)
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)
cli(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)]
-----------
> add --help
Usage: test.py add [OPTIONS]
this is the add command
Options:
--overwrite
--help Show this message and exit.
-----------
> --help
Usage: test.py [OPTIONS] COMMAND [ARGS]...
this is a tool that has an add and remove command
Options:
--directory TEXT
--help Show this message and exit.
Commands:
add this is the add command
remove this is the remove command
-----------
> --directory a_dir add
a_dir
add overwrite=False