使命令可用于python click中的两个组? [英] Make a command available for two groups in python click?
问题描述
我正在使用click编写Python中的cli程序,我需要编写如下内容:
I'm using click to write a cli program in Python, and I need to write something like this:
import click
@click.group()
def root():
"""root"""
pass
@root.group()
def cli():
"""test"""
pass
@root.group()
def cli2():
"""test"""
pass
@cli.command('test1')
@cli2.command('test1')
def test1():
"""test2"""
print 1234
return
root()
但是这将失败:
TypeError:尝试两次将回调转换为命令.
TypeError: Attempted to convert a callback into a command twice.
如何在多个组之间共享命令?
How can I share the command between multiple groups?
推荐答案
group.command()
装饰器是执行两个功能的快捷方式.一种是创建命令,另一种是将命令附加到组.
The group.command()
decorator is a short cut which performs two functions. One is to create a command, the other is to attach the command to a group.
因此,要与多个组共享一个命令,可以为一个组装饰命令,例如:
So, to share a command with multiple groups, you can decorate the command for one group like:
@cli.command('test1')
然后,由于已经创建了命令,因此您可以简单地将click命令对象添加到其他组中,例如:
Then, since the command has already been created, you can simply add the click command object to other groups like:
cli2.add_command(test1)
测试代码:
import click
@click.group()
def root():
"""root"""
pass
@root.group()
def cli1():
click.echo('cli1')
@root.group()
def cli2():
click.echo('cli2')
@cli1.command('test1')
@click.argument('arg1')
def test1(arg1):
click.echo('test1: %s' % arg1)
cli2.add_command(test1)
root('cli2 test1 an_arg'.split())
结果:
cli2
test1: an_arg
这篇关于使命令可用于python click中的两个组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!