我想要两个选项和三个命令,我可以在命令后接受参数。
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
答案 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