python - 如何多次动态调用命令的子命令?
问题描述
我的 Click 7.0 应用程序有一组,有多个命令,由主 cli 函数调用,如下所示:
代码:
import sys
import click
@click.group()
def cli():
"""This is cli helptext"""
click.echo('cli called')
@cli.group(chain=True, no_args_is_help=False)
@click.option('-r', '--repeat', default=1, type=click.INT, help='repeat helptext')
def chainedgroup(repeat):
"""This is chainedgroup helptext"""
top = sys.argv[2]
bottom = sys.argv[3:]
click.echo('chainedgroup code called')
for _ in range(repeat):
chainedgroup.main(bottom, top, standalone_mode=False)
@chainedgroup.command()
def command1():
"""This is command1 helptext"""
click.echo('command1 called')
@chainedgroup.command()
@click.option('-o', '--option')
def command2(option):
"""This is command2 helptext"""
click.echo('command2 called with {0}'.format(option))
跑:
$ testcli chainedgroup --repeat 2 command1
$ testcli chainedgroup -r 3 command1 command2 -o test
预期结果:
cli called
chainedgroup code called
command1 called
command1 called
----------
cli called
chainedgroup code called
command1 called
command2 called with test
command1 called
command2 called with test
command1 called
command2 called with test
实际结果:
案例 #1 给了我一个Missing command
错误,而案例 #2 以RecursionError
.
我确定我确定Command.main()
是正确的调用方法。我究竟做错了什么?
解决方案
如果您创建自定义click.Group
类,则可以覆盖该invoke()
方法以多次调用命令。
自定义类:
class RepeatMultiCommand(click.Group):
def invoke(self, ctx):
old_callback = self.callback
def new_callback(*args, **kwargs):
# only call the group callback once
if repeat_number == 0:
return old_callback(*args, **kwargs)
self.callback = new_callback
# call invoke the desired number of times
for repeat_number in range(ctx.params['repeat']):
new_ctx = copy.deepcopy(ctx)
super(RepeatMultiCommand, self).invoke(new_ctx)
self.callback = old_callback
要使用自定义类:
将带有参数的自定义类传递给.group()
装饰器,cls
例如:
@cli.group(chain=True, no_args_is_help=False, cls=RepeatMultiCommand)
@click.option('-r', '--repeat', default=1, type=click.INT,
help='repeat helptext')
def chainedgroup(repeat):
....
这是如何运作的?
这是因为 click 是一个设计良好的 OO 框架。@click.group()
装饰器通常实例化一个对象click.Group
,但允许使用cls
参数覆盖此行为。因此,从click.Group
我们自己的类中继承并覆盖所需的方法是一件相对容易的事情。
在这种情况下,我们覆盖click.Group.invoke()
. 在我们的invoke()
中,我们钩住了组回调,这样我们就可以让它只被调用一次,然后我们调用它super().invoke()
的repeat
次数。
测试代码:
import click
import copy
import sys
@click.group()
def cli():
"""This is cli helptext"""
click.echo('cli called')
@cli.group(chain=True, no_args_is_help=False, cls=RepeatMultiCommand)
@click.option('-r', '--repeat', default=1, type=click.INT,
help='repeat helptext')
def chainedgroup(repeat):
"""This is chainedgroup helptext"""
click.echo('chainedgroup code called')
@chainedgroup.command()
def command1():
"""This is command1 helptext"""
click.echo('command1 called')
@chainedgroup.command()
@click.option('-o', '--option')
def command2(option):
"""This is command2 helptext"""
click.echo('command2 called with {0}'.format(option))
if __name__ == "__main__":
commands = (
'chainedgroup --repeat 2 command1',
'chainedgroup -r 3 command1 command2 -o test',
'chainedgroup command1',
'chainedgroup --help',
'--help',
)
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)]
-----------
> chainedgroup --repeat 2 command1
cli called
chainedgroup code called
command1 called
command1 called
-----------
> chainedgroup -r 3 command1 command2 -o test
cli called
chainedgroup code called
command1 called
command2 called with test
command1 called
command2 called with test
command1 called
command2 called with test
-----------
> chainedgroup command1
cli called
chainedgroup code called
command1 called
-----------
> chainedgroup --help
cli called
Usage: test.py chainedgroup [OPTIONS] COMMAND1 [ARGS]... [COMMAND2
[ARGS]...]...
This is chainedgroup helptext
Options:
-r, --repeat INTEGER repeat helptext
--help Show this message and exit.
Commands:
command1 This is command1 helptext
command2 This is command2 helptext
-----------
> --help
Usage: test.py [OPTIONS] COMMAND [ARGS]...
This is cli helptext
Options:
--help Show this message and exit.
Commands:
chainedgroup This is chainedgroup helptext
推荐阅读
- python - 填充pyspark数据框空值
- python - 为什么keras模型不能在python的多进程池中运行?
- java - 如何在 REST API Java 中忽略响应中的某些字段
- javascript - Javascript 自定义事件的大小是否有限?
- jquery - 使用 jQuery - ASP.NET Core MVC 通过单击按钮获取表格行的值
- swift - 在 Swift 中访问泛型参数的类型值
- android - 第一个支持多屏显示的 Android 版本是哪个?
- plsql - DBeaver 中变量名的建议
- python - 如何计算用户 ID 在 Dynamodb 中出现的次数
- routes - Anylogic 离散事件建模:如何根据代理是空闲还是忙碌将代理路由到多个资源单元?