在click python模块中获取命令后的参数

时间:2018-05-06 01:48:33

标签: python python-3.x python-click

我想要两个选项和三个命令,我可以在命令后接受参数。

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

实施例

myworkspace.py --removedigits upper Hello12 There12

预期产出:

HELLO THERE

1 个答案:

答案 0 :(得分:1)

使这项工作的关键是将removedigits值保存到上下文中,例如:

代码:

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

然后你可以像以下一样进行检索:

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

测试代码:

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

结果:

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