20

我知道它是新的,但我非常喜欢click的外观并且很想使用它,但我不知道如何将变量从 main 方法传递给其他方法。我是否使用不正确,或者此功能尚不可用?看起来很基础,所以我相信它会在那里,但这些东西只出现了一段时间,所以可能不会。

import click

@click.option('--username', default='', help='Username')
@click.option('--password', default='', help='Password')
@click.group()
def main(**kwargs):
    print("This method has these arguments: " + str(kwargs))


@main.command('do_thingy')
def do_thing(**kwargs):
    print("This method has these arguments: " + str(kwargs))


@main.command('do_y')
def y(**kwargs):
    print("This method has these arguments: " + str(kwargs))


@main.command('do_x')
def x(**kwargs):
    print("This method has these arguments: " + str(kwargs))


main()

所以我的问题是,如何让其他方法可以使用用户名和密码选项

4

2 回答 2

32

感谢@nathj07 为我指明了正确的方向。这是答案:

import click


class User(object):
    def __init__(self, username=None, password=None):
        self.username = username
        self.password = password


@click.group()
@click.option('--username', default='Naomi McName', help='Username')
@click.option('--password', default='b3$tP@sswerdEvar', help='Password')
@click.pass_context
def main(ctx, username, password):
    ctx.obj = User(username, password)
    print("This method has these arguments: " + str(username) + ", " + str(password))


@main.command()
@click.pass_obj
def do_thingy(ctx):
    print("This method has these arguments: " + str(ctx.username) + ", " + str(ctx.password))


@main.command()
@click.pass_obj
def do_y(ctx):
    print("This method has these arguments: " + str(ctx.username) + ", " + str(ctx.password))


@main.command()
@click.pass_obj
def do_x(ctx):
    print("This method has these arguments: " + str(ctx.username) + ", " + str(ctx.password))


main()
于 2014-05-14T13:57:02.170 回答
-8

有什么理由不能使用argparse吗?我应该认为它可以让你实现你正在寻找的东西,尽管方式略有不同。

至于使用 click 那么也许 pass_obj 会帮助

于 2014-05-13T12:21:07.407 回答