python单击中2个不同函数的完全相同的选项

时间:2016-11-23 00:45:29

标签: python python-2.7 python-click

我正在使用Python 2click编写工具,该工具在硬件中读/写寄存器。我有两个函数接受完全相同的选项。不同之处在于它们处理输入并将输出直接输出到不同的设备。

这是我到目前为止所做的:

@cli.command()
@click.option('--r0', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)
@click.option('--r1', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)
@click.option('--r2', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)
def mydevice1(r0, r1, r2):
    # Handle inputs for device 1
    click.echo('myfunc1')

@cli.command()   
@click.option('--r0', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)
@click.option('--r1', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)
@click.option('--r2', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)
def mydevice2(r0, r1, r2):
    # Handle inputs for device 2
    click.echo('myfunc2')

两个函数都将以相同的方式处理输入,唯一的区别是它们将处理信息传递给不同的设备。换句话说,我想拥有的是

@click.option('--r0', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)
@click.option('--r1', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)
@click.option('--r2', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)
def handle_common_options(r0, r1, r2):
    # Handle common options
    pass

@cli.command()
def mydevice1():
    handle_common_options()
    # pass processed options to device 1

@cli.command()
def mydevice2():
    handle_common_options()
    # pass processed options to device 2

这可能吗?

1 个答案:

答案 0 :(得分:1)

确定。

@decorator
def f():
    pass

装置

def f():
    pass
f = decorator(f)

这样:

decorator0 = cli.command()
decorator1 = click.option('--r0', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)
decorator2 = click.option('--r1', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)
decorator3 = click.option('--r2', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)

common_decorator = lambda f: decorator0(decorator1(decorator2(decorator3(f))))

@common_decorator
def mydevice1(r0, r1, r2):
    click.echo('myfunc1')

@common_decorator
def mydevice2(r0, r1, r2):
    click.echo('myfunc2')

没有lambda:

def common_decorator(f):
    return decorator0(decorator1(decorator2(decorator3(f))))