简体   繁体   English

如何使用python-click为同一组中的cmd使用相同的选项

[英]How to use same options for cmd in the same group by using python-click

I have code like below, both foo and bar have a user option and I need to write: 我有下面的代码,foo和bar都有用户选项,我需要写:

@click.option('--user', default='*')

twice for each function. 每个功能两次。

But I actually have a lot of cmds like this, so it is a lot of repeated code. 但实际上我有很多这样的cmds,所以它是很多重复的代码。

@click.group(help="cmd group")
def main():
    pass


@click.command(name='foo')
@click.option('--user', default='*')
def foo(user):
    click.secho(user, fg='green')


@click.command(name='bar')
@click.option('--user', default='*')
def bar(user):
    click.secho(user, fg='green')


main.add_command(foo)
main.add_command(bar)

What I want is to add the same option to one place in the group of cmd. 我想要的是将相同的选项添加到cmd组中的一个位置。 ow can I do this using click? 我可以点击这么做吗?

pass it in the context: 在上下文中传递它:

@click.group(help="cmd group")
@click.option('--user', default='*')
@click.pass_context
def main(ctx, user):
    ctx.obj = {'user': user}


@click.command(name='foo')
@click.pass_context
def foo(ctx):
    click.secho(ctx.obj['user'], fg='green')


@click.command(name='bar')
@click.pass_context
def bar(ctx):
    click.secho(ctx.obj['user'], fg='green')


main.add_command(foo)
main.add_command(bar)

mycli --user cats bar will echo cats from the bar subcommand mycli --user cats bar将从bar子命令回mycli --user cats bar

Method 1. I suppose the name of first parameter of @click.option() is para . 方法1.我认为@ click.option()的para一个参数的名称是para

USER_DEFAULT = {'para' : '--user', 'default' : '*'}

@click.option(**USER_DEFAULT)

Method 2. Wrap it in you own decorator filled with default parameters. 方法2.将它包装在你自己的装饰有默认参数的装饰器中。

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

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