gpt4 book ai didi

python - 如何使用 Python 的 click (Command Line Interface Creation Kit) 包将变量传递给其他方法

转载 作者:太空狗 更新时间:2023-10-29 17:28:12 24 4
gpt4 key购买 nike

我知道它是新的,但我喜欢 click 的外观很多并且很想使用它,但我不知道如何将变量从 main 方法传递给其他方法。我是不是用错了,还是这个功能还不可用?看起来很基本,所以我确定它会在那里,但是这个东西只出了一个 little while所以也许不是。

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

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

最佳答案

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

关于python - 如何使用 Python 的 click (Command Line Interface Creation Kit) 包将变量传递给其他方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23626972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com