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

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


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

import clickclass 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_contextdef main(ctx, username, password):    ctx.obj = User(username, password)    print("This method has these arguments: " + str(username) + ", " + str(password))@main.command()@click.pass_objdef do_thingy(ctx):    print("This method has these arguments: " + str(ctx.username) + ", " + str(ctx.password))@main.command()@click.pass_objdef do_y(ctx):    print("This method has these arguments: " + str(ctx.username) + ", " + str(ctx.password))@main.command()@click.pass_objdef do_x(ctx):    print("This method has these arguments: " + str(ctx.username) + ", " + str(ctx.password))main()


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