Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take arguments after command in click python module

I wanted two options and three commands, where I could take arguments after command.

import click

@click.group()
@click.option('--removedigits/--removenodigits',default=False,help="To remove digits or not")
    def cli(removedigits):
        pass


@cli.command('uppercase')
@click.argument('arguments', nargs=-1)

def processor(arguments,removedigits):
    print(arguments)


@cli.command('lowercase')
@click.argument('arguments', nargs=-1)

def processor1(arguments,removedigits):        
    print(arguments)


if __name__ == '__main__':
    cli()               

Example:

myworkspace.py --removedigits upper Hello12 There12

Expected Output:

HELLO THERE

1 Answers

The key to making this work is to save the removedigits value into the context with something like:

Code:

@click.pass_context
def cli(ctx, removedigits):
    ctx.obj = dict(removedigits=removedigits)

Then you can retreive it like:

@click.pass_context
def upper(ctx, arguments):
    click.echo(ctx.obj['removedigits'])

Test Code:

import click


@click.group()
@click.option('--removedigits/--removenodigits', default=False,
              help="To remove digits or not")
@click.pass_context
def cli(ctx, removedigits):
    ctx.obj = dict(removedigits=removedigits)


def removedigits(ctx, a_string):
    if ctx.obj['removedigits']:
        a_string = ''.join(c for c in a_string if not c.isdigit())
    return a_string


@cli.command()
@click.argument('arguments', nargs=-1)
@click.pass_context
def upper(ctx, arguments):
    click.echo(ctx.obj['removedigits'])
    click.echo(removedigits(ctx, ' '.join(arguments).upper()))


@cli.command()
@click.argument('arguments', nargs=-1)
@click.pass_context
def lower(ctx, arguments):
    click.echo(ctx.obj['removedigits'])
    click.echo(removedigits(ctx, ' '.join(arguments).lower()))


if __name__ == '__main__':
    commands = (
        '--removedigits lower Hi Mom',
        '--removedigits upper Hi Mom',
        '--removedigits upper Hi1 Mom2',
        '--removenodigits upper Hi Mom',
        '--removenodigits upper Hi1 Mom2',
        'upper Hi Mom',
        'upper Hi1 Mom2',
        '--help',
    )

    import sys, time
    time.sleep(1)
    print('Click Version: {}'.format(click.__version__))
    print('Python Version: {}'.format(sys.version))
    for cmd in commands:
        try:
            time.sleep(0.1)
            print('-----------')
            print('> ' + cmd)
            time.sleep(0.1)
            cli(cmd.split())

        except BaseException as exc:
            if str(exc) != '0' and \
                    not isinstance(exc, (click.ClickException, SystemExit)):
                raise

Results:

Click Version: 6.7
Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
-----------
> --removedigits lower Hi Mom
True
hi mom
-----------
> --removedigits upper Hi Mom
True
HI MOM
-----------
> --removedigits upper Hi1 Mom2
True
HI MOM
-----------
> --removenodigits upper Hi Mom
False
HI MOM
-----------
> --removenodigits upper Hi1 Mom2
False
HI1 MOM2
-----------
> upper Hi Mom
False
HI MOM
-----------
> upper Hi1 Mom2
False
HI1 MOM2
-----------
> --help
Usage: test.py [OPTIONS] COMMAND [ARGS]...

Options:
  --removedigits / --removenodigits
                                  To remove digits or not
  --help                          Show this message and exit.

Commands:
  lower
  upper
like image 123
Stephen Rauch Avatar answered Aug 29 '26 18:08

Stephen Rauch