How do I pass variables to other methods using Python's click (Command Line Interface Creation Kit) package

帅比萌擦擦* 提交于 2019-12-18 12:18:11

问题


I know it's new, but I like the look of click a lot and would love to use it, but I can't work out how to pass variables from the main method to other methods. Am I using it incorrectly, or is this functionality just not available yet? Seems pretty fundamental, so I'm sure it will be in there, but this things only been out a little while so maybe not.

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

So my question is, how do I get the username and password options to be available to the other methods


回答1:


Thanks to @nathj07 for pointing me in the right direction. Here's the answer:

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



回答2:


Is there any reason you can't use argparse? I should think it would allow you to achieve what you are looking for, though in a slightly different manner.

As for using click then perhaps the pass_obj will help you out



来源:https://stackoverflow.com/questions/23626972/how-do-i-pass-variables-to-other-methods-using-pythons-click-command-line-inte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!