如何使用Python的单击(命令行界面创建工具包)将变量传递给其他方法

Dar*_*ren 14 python python-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()
Run Code Online (Sandbox Code Playgroud)

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

Dar*_*ren 24

感谢@ 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()
Run Code Online (Sandbox Code Playgroud)