Skip to content Skip to sidebar Skip to footer

How Do I Pass Variables To Other Methods Using Python's Click (command Line Interface Creation Kit) Package

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 incorr

Solution 1:

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

import click


classUser(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_contextdefmain(ctx, username, password):
    ctx.obj = User(username, password)
    print("This method has these arguments: " + str(username) + ", " + str(password))


@main.command()@click.pass_objdefdo_thingy(ctx):
    print("This method has these arguments: " + str(ctx.username) + ", " + str(ctx.password))


@main.command()@click.pass_objdefdo_y(ctx):
    print("This method has these arguments: " + str(ctx.username) + ", " + str(ctx.password))


@main.command()@click.pass_objdefdo_x(ctx):
    print("This method has these arguments: " + str(ctx.username) + ", " + str(ctx.password))


main()

Solution 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

Post a Comment for "How Do I Pass Variables To Other Methods Using Python's Click (command Line Interface Creation Kit) Package"