简体   繁体   English

python click中2个不同功能的完全相同的选项

[英]exactly same options for 2 different functions in python click

I'm writing a tool using Python 2 and click which reads/writes registers in hardware. 我正在使用Python 2编写工具, 然后单击该工具在硬件中读取/写入寄存器。 I have two functions that accept exactly the same options. 我有两个函数接受完全相同的选项。 The difference is that they process input and direct output to a different devices. 不同之处在于它们处理输入并将输出直接输出到其他设备。

Here is what I have so far: 这是我到目前为止的内容:

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

Both of the functions will handle inputs in the same way, the only difference is that they will pass handled info to different devices. 这两个功能将以相同的方式处理输入,唯一的区别是它们会将处理过的信息传递给不同的设备。 In other words what I'd like to have is 换句话说,我想拥有的是

@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

Is this possible? 这可能吗?

sure. 当然。

@decorator
def f():
    pass

means 手段

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

so: 所以:

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

without a lambda: 没有lambda:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM