Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 452
Darren Avatar asked May 13 '14 09:05

Darren


People also ask

What is click command Python?

Click is a Python package for creating beautiful command line interfaces in a composable way with as little code as necessary. It's the “Command Line Interface Creation Kit”. It's highly configurable but comes with sensible defaults out of the box.

What is command line arguments in Python?

Python Command line arguments are input parameters passed to the script when executing them. Almost all programming language provide support for command line arguments. Then we also have command line options to set some specific options for the program.


1 Answers

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()
like image 71
Darren Avatar answered Oct 18 '22 05:10

Darren