I write CLI with Click in python. I want to invoke a command with another command in Click. I saw it in Click documentation so I write below code:
import click
def convert_click_option_to_function_argument(click_args):
function_arguments = {}
for index, value in enumerate(click_args):
if not value.startswith('--'):
continue
if index+1 < len(click_args):
if not click_args[index+1].startswith('--'):
function_argument[value.replace('--','',1)] = click_args[index+1]
else:
function_argument[value.replace('--','',1)] = True
else:
function_argument[value.replace('--','',1)] = True
return function_argument
cli = click.Group()
@cli.command()
@click.option('--count', type=int, required=True)
@click.option('--file_name', type=click.Path(exists=True), required=True)
def test(count: int, file_name: str) -> None:
click.echo('Count: {}'.format(count))
click.echo('File Name: {}'.format(file_name))
@cli.command(
context_settings=dict(
ignore_unknown_options=True,
allow_extra_args=True,
))
@click.option('--sequential/--parallel', default='sequential')
@click.argument('my_command', nargs=1, required=True)
@click.pass_context
def for_command(ctx, my_command: str, sequential: bool) -> None:
if sequential is True:
click.echo('sequential is True')
arguments = convert_click_option_to_function_argument(ctx.args)
ctx.invoke(eval(my_command), **arguments)
cli()
This module that name is "my_file.py" so I run it based below command:
python3 my_file.py for_command --sequential test --count 100 --file_name test.py
When I run callback in invoke function I could not validate the argument's function for example in this example test.py does not exist. How can I validate the args of invoke command before invoke command?