通过一些新的管道可以做到这一点。
如何??
您可以继承click.Group
然后将创建的类传递给click.group()
喜欢:
@click.group(cls=GroupWithCommandOptions)
在新类中,可以将组上的选项应用于命令进行解析,然后在命令调用期间,可以使用适当的选项调用组函数。
新组类:
import click
class GroupWithCommandOptions(click.Group):
""" Allow application of options to group with multi command """
def add_command(self, cmd, name=None):
""" Hook the added command and put the group options on the command """
click.Group.add_command(self, cmd, name=name)
# add the group parameters to the command
for param in self.params:
cmd.params.append(param)
# hook the command's invoke with our own
cmd.invoke = self.build_command_invoke(cmd.invoke)
self.invoke_without_command = True
def build_command_invoke(self, original_invoke):
def command_invoke(ctx):
""" insert invocation of group function """
# separate the group parameters
ctx.obj = dict(_params=dict())
for param in self.params:
name = param.name
ctx.obj['_params'][name] = ctx.params[name]
del ctx.params[name]
# call the group function with its parameters
params = ctx.params
ctx.params = ctx.obj['_params']
self.invoke(ctx)
ctx.params = params
# now call (invoke) the original command
original_invoke(ctx)
return command_invoke
测试代码:
# Pass new group class to our group which needs options
@click.group(cls=GroupWithCommandOptions)
@click.option('--username')
def cli1(username):
click.echo(username)
@cli1.command()
def something():
click.echo('howdy')
@click.group()
def cli2():
pass
@cli2.command()
def somethingelse():
click.echo('doody')
cli = click.CommandCollection(sources=[cli1, cli2])
if __name__ == '__main__':
cli('something --username hi'.split())
结果:
hi
howdy