1

I would like to integrate a python CLI written using click into a python CLI application built using another framework. Rewriting the calling application is not an option.

As part of the integration, I need to invoke the click CLI from within code passing the arguments it should consume directly. How do I do this?

For a concrete example, consider that I'd invoke this as foobar theclickcli <args> where foobar is the CLI not written in click and theclickcli is a subcommand that should invoke my click CLI with its arguments (<args>).

I see that click offers the click.testing.CLIRunner class which allows invoking a group or command. However, the documentation notes that:

"...[this] should really only be used for testing as they change the entire interpreter state for simplicity and are not in any way thread-safe".

Is there an "idiomatic" way of invoking a click CLI (not just a subcommand) given an argv argument list like in argparse?

3
  • Is there a must for you to have it integrated into the same python process? What do you want to.do with the stdandard input/output of your click CLI? Why don't you just invoke the whole application as subprocess? Commented Apr 27, 2023 at 4:46
  • Yes it must be part of the same python process (context: I'm creating a conda plugin that uses pluggy but the plugin has a CLI fully built using click) Commented Apr 27, 2023 at 17:50
  • you can invoke a Click CLI from within your code using the click.Context and click.Command.invoke() method. Commented Apr 27, 2023 at 20:54

1 Answer 1

-1

You can create a new Context object manually and invoke the command using the Context.invoke() method. example:

import click

@click.command()
@click.option('--name', default='World', help='Who to greet')
def hello(name):
    click.echo(f'Hello, {name}!')

def invoke_click_command(args):
    ctx = click.Context(hello)
    ctx.invoke(hello, args=args)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.