如何使用Python的click包将变量传递给其他方法

21 投票
2 回答
12659 浏览
提问于 2025-04-18 06:23

我知道这个东西是新的,但我非常喜欢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()

所以我的问题是,怎么才能让用户名和密码的选项在其他方法中也能用呢?

2 个回答

-8

你有没有想过为什么不能用 argparse 呢?我觉得它应该能帮你实现你想要的功能,只是方式可能有点不同。

如果你选择使用 click,那么 也许 pass_obj 会对你有帮助

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

撰写回答