单击:如何将操作应用于所有命令和子命令但允许命令选择退出?
Click: how do I apply an action to all commands and subcommands but allow a command to opt-out?
我有一个案例,我想为我的大多数点击命令和子命令自动 运行 一个常用函数 check_upgrade()
,但在某些情况下我不想 运行 它。我在想我可以有一个装饰器,可以为 check_upgrade()
不应该 运行.
的命令添加(例如 @bypass_upgrade_check
)
我希望得到类似的东西(感谢 的最初想法):
def do_upgrade():
print "Performing upgrade"
def bypass_upgrade_check(func):
setattr(func, "do_upgrade_check", False)
return func
@click.group()
@click.pass_context
def common(ctx):
sub_cmd = ctx.command.commands[ctx.invoked_subcommand]
if getattr(sub_cmd, "do_upgrade_check", True):
do_upgrade()
@bypass_upgrade_check
@common.command()
def top_cmd1():
# don't run do_upgrade() on top level command
pass
@common.command()
def top_cmd2():
# DO run do_upgrade() on top level command
pass
@common.group()
def sub_cmd_group():
pass
@bypass_upgrade_check
@sub_cmd.command()
def sub_cmd1():
# don't run do_upgrade() on second-level command
pass
@sub.command()
def sub_cmd2():
# DO run do_upgrade() on second-level command
pass
不幸的是,这仅适用于顶级命令,因为 ctx.invoked_subcommand
指的是 sub_cmd_group
而不是 sub_cmd1
或 sub_cmd2
。
有没有一种方法可以递归搜索子命令,或者使用自定义组来同时使用顶级命令和子命令来实现此功能?
解决这个问题的一种方法是构建一个与自定义 click.Group
class:
配对的自定义装饰器
自定义装饰器生成器:
def make_exclude_hook_group(callback):
""" for any command that is not decorated, call the callback """
hook_attr_name = 'hook_' + callback.__name__
class HookGroup(click.Group):
""" group to hook context invoke to see if the callback is needed"""
def invoke(self, ctx):
""" group invoke which hooks context invoke """
invoke = ctx.invoke
def ctx_invoke(*args, **kwargs):
""" monkey patched context invoke """
sub_cmd = ctx.command.commands[ctx.invoked_subcommand]
if not isinstance(sub_cmd, click.Group) and \
getattr(sub_cmd, hook_attr_name, True):
# invoke the callback
callback()
return invoke(*args, **kwargs)
ctx.invoke = ctx_invoke
return super(HookGroup, self).invoke(ctx)
def group(self, *args, **kwargs):
""" new group decorator to make sure sub groups are also hooked """
if 'cls' not in kwargs:
kwargs['cls'] = type(self)
return super(HookGroup, self).group(*args, **kwargs)
def decorator(func=None):
if func is None:
# if called other than as decorator, return group class
return HookGroup
setattr(func, hook_attr_name, False)
return decorator
使用装饰器生成器:
要使用装饰器,我们首先需要像这样构建装饰器:
bypass_upgrade_check = make_exclude_hook_group(do_upgrade)
然后我们需要将它作为自定义 class 到 click.group()
来使用,例如:
@click.group(cls=bypass_upgrade_check())
...
最后,我们可以将任何命令或子命令修饰到不需要使用回调的组,例如:
@bypass_upgrade_check
@my_group.command()
def my_click_command_without_upgrade():
...
这是如何工作的?
之所以可行,是因为 click 是一个设计良好的 OO 框架。 @click.group()
装饰器通常实例化一个 click.Group
对象,但允许使用 cls
参数覆盖此行为。因此,在我们自己的 class 中继承 click.Group
并覆盖所需的方法是一件相对容易的事情。
在这种情况下,我们构建了一个装饰器,它在任何不需要调用回调的点击函数上设置一个属性。然后在我们的自定义组中,我们猴子修补 click.Context.invoke()
我们的上下文,如果即将执行的命令尚未被装饰,我们调用回调。
测试代码:
import click
def do_upgrade():
print("Performing upgrade")
bypass_upgrade_check = make_exclude_hook_group(do_upgrade)
@click.group(cls=bypass_upgrade_check())
@click.pass_context
def cli(ctx):
pass
@bypass_upgrade_check
@cli.command()
def top_cmd1():
click.echo('cmd1')
@cli.command()
def top_cmd2():
click.echo('cmd2')
@cli.group()
def sub_cmd_group():
click.echo('sub_cmd_group')
@bypass_upgrade_check
@sub_cmd_group.command()
def sub_cmd1():
click.echo('sub_cmd1')
@sub_cmd_group.command()
def sub_cmd2():
click.echo('sub_cmd2')
if __name__ == "__main__":
commands = (
'top_cmd1',
'top_cmd2',
'sub_cmd_group sub_cmd1',
'sub_cmd_group sub_cmd2',
'--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)]
-----------
> top_cmd1
cmd1
-----------
> top_cmd2
Performing upgrade
cmd2
-----------
> sub_cmd_group sub_cmd1
sub_cmd_group
sub_cmd1
-----------
> sub_cmd_group sub_cmd2
Performing upgrade
sub_cmd_group
sub_cmd2
-----------
> --help
Usage: test.py [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
sub_cmd_group
top_cmd1
top_cmd2
我有一个案例,我想为我的大多数点击命令和子命令自动 运行 一个常用函数 check_upgrade()
,但在某些情况下我不想 运行 它。我在想我可以有一个装饰器,可以为 check_upgrade()
不应该 运行.
@bypass_upgrade_check
)
我希望得到类似的东西(感谢
def do_upgrade():
print "Performing upgrade"
def bypass_upgrade_check(func):
setattr(func, "do_upgrade_check", False)
return func
@click.group()
@click.pass_context
def common(ctx):
sub_cmd = ctx.command.commands[ctx.invoked_subcommand]
if getattr(sub_cmd, "do_upgrade_check", True):
do_upgrade()
@bypass_upgrade_check
@common.command()
def top_cmd1():
# don't run do_upgrade() on top level command
pass
@common.command()
def top_cmd2():
# DO run do_upgrade() on top level command
pass
@common.group()
def sub_cmd_group():
pass
@bypass_upgrade_check
@sub_cmd.command()
def sub_cmd1():
# don't run do_upgrade() on second-level command
pass
@sub.command()
def sub_cmd2():
# DO run do_upgrade() on second-level command
pass
不幸的是,这仅适用于顶级命令,因为 ctx.invoked_subcommand
指的是 sub_cmd_group
而不是 sub_cmd1
或 sub_cmd2
。
有没有一种方法可以递归搜索子命令,或者使用自定义组来同时使用顶级命令和子命令来实现此功能?
解决这个问题的一种方法是构建一个与自定义 click.Group
class:
自定义装饰器生成器:
def make_exclude_hook_group(callback):
""" for any command that is not decorated, call the callback """
hook_attr_name = 'hook_' + callback.__name__
class HookGroup(click.Group):
""" group to hook context invoke to see if the callback is needed"""
def invoke(self, ctx):
""" group invoke which hooks context invoke """
invoke = ctx.invoke
def ctx_invoke(*args, **kwargs):
""" monkey patched context invoke """
sub_cmd = ctx.command.commands[ctx.invoked_subcommand]
if not isinstance(sub_cmd, click.Group) and \
getattr(sub_cmd, hook_attr_name, True):
# invoke the callback
callback()
return invoke(*args, **kwargs)
ctx.invoke = ctx_invoke
return super(HookGroup, self).invoke(ctx)
def group(self, *args, **kwargs):
""" new group decorator to make sure sub groups are also hooked """
if 'cls' not in kwargs:
kwargs['cls'] = type(self)
return super(HookGroup, self).group(*args, **kwargs)
def decorator(func=None):
if func is None:
# if called other than as decorator, return group class
return HookGroup
setattr(func, hook_attr_name, False)
return decorator
使用装饰器生成器:
要使用装饰器,我们首先需要像这样构建装饰器:
bypass_upgrade_check = make_exclude_hook_group(do_upgrade)
然后我们需要将它作为自定义 class 到 click.group()
来使用,例如:
@click.group(cls=bypass_upgrade_check())
...
最后,我们可以将任何命令或子命令修饰到不需要使用回调的组,例如:
@bypass_upgrade_check
@my_group.command()
def my_click_command_without_upgrade():
...
这是如何工作的?
之所以可行,是因为 click 是一个设计良好的 OO 框架。 @click.group()
装饰器通常实例化一个 click.Group
对象,但允许使用 cls
参数覆盖此行为。因此,在我们自己的 class 中继承 click.Group
并覆盖所需的方法是一件相对容易的事情。
在这种情况下,我们构建了一个装饰器,它在任何不需要调用回调的点击函数上设置一个属性。然后在我们的自定义组中,我们猴子修补 click.Context.invoke()
我们的上下文,如果即将执行的命令尚未被装饰,我们调用回调。
测试代码:
import click
def do_upgrade():
print("Performing upgrade")
bypass_upgrade_check = make_exclude_hook_group(do_upgrade)
@click.group(cls=bypass_upgrade_check())
@click.pass_context
def cli(ctx):
pass
@bypass_upgrade_check
@cli.command()
def top_cmd1():
click.echo('cmd1')
@cli.command()
def top_cmd2():
click.echo('cmd2')
@cli.group()
def sub_cmd_group():
click.echo('sub_cmd_group')
@bypass_upgrade_check
@sub_cmd_group.command()
def sub_cmd1():
click.echo('sub_cmd1')
@sub_cmd_group.command()
def sub_cmd2():
click.echo('sub_cmd2')
if __name__ == "__main__":
commands = (
'top_cmd1',
'top_cmd2',
'sub_cmd_group sub_cmd1',
'sub_cmd_group sub_cmd2',
'--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)]
-----------
> top_cmd1
cmd1
-----------
> top_cmd2
Performing upgrade
cmd2
-----------
> sub_cmd_group sub_cmd1
sub_cmd_group
sub_cmd1
-----------
> sub_cmd_group sub_cmd2
Performing upgrade
sub_cmd_group
sub_cmd2
-----------
> --help
Usage: test.py [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
sub_cmd_group
top_cmd1
top_cmd2