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

21

虽然它很新,但我喜欢Click的外观,并且想使用它,但我不知道如何将变量从主方法传递到其他方法。我是在错误地使用它吗?还是这个功能还没有可用?这似乎非常基本,所以我相信它将会被添加进去,但是这个东西只发布了不久,也许还没有。

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()
所以我的问题是,我该如何使用户名和密码选项对其他方法可用。

我无法帮助你。只是想建议你考虑看一下 docopt 命令行解析器。 - Jan Vlcinsky
2个回答

34

感谢 @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()

-8

你不能使用argparse吗?我认为它可以让你以稍微不同的方式实现你想要的目标。

至于使用click,也许pass_obj能帮助你解决问题。


@Julius,但是你使用了subparses,这是另一种实现类似功能的方法。 - The_Ham

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接