[Python] How can I validate args of the click "invoke" function when a command invokes another...

Discussão em 'Python' iniciado por Stack, Junho 18, 2025.

  1. Stack

    Stack Membro Participativo

    I write a CLI with Click in Python. I want to invoke a command with another command. I saw it in the Click documentation so I wrote 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 is named "my_file.py" so I run it using 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?

    Continue reading...

Compartilhe esta Página