Make a command available for two groups in python click?

こ雲淡風輕ζ 提交于 2019-12-11 02:50:46

问题


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()

but this will fail with:

TypeError: Attempted to convert a callback into a command twice.

How can I share the command between multiple groups?


回答1:


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')

Then, since the command has already been created, you can simply add the click command object to other groups like:

cli2.add_command(test1)

Test Code:

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())

Results:

cli2
test1: an_arg


来源:https://stackoverflow.com/questions/45500223/make-a-command-available-for-two-groups-in-python-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!