How do I manually invoke click CLIs from within a Python calling context with parameters?

51 Views Asked by At

In order to set up automatic function aliases in setuptools, it's necessary to wrap all args in some kind of function. If I am using a click interface, I'll need some way to parameterize specific calls to the click interface in order to alias them.


In a hello world format, how do I call a Python click interface CLI:

# cli.py
import click
@click.group()
def cli():
  """Help Message"""
  pass

within Python, rather than on the command line, with an argument so that:

# command line
$ python3 cli.py --help
Help Message
# python interpreter
>>> cli(???) # replace ??? w/ the correct argument
Help Message

the "Help Message" is displayed when I call the CLI from within a python3 runtime context?

1

There are 1 best solutions below

0
Chris On

Although there is an existing related question, there is a lot of discussion. This solution addresses the problem.

tldr: a click cli group accepts an arg list of strings.

import click

@click.group()
def cli():
    """ A click group """
    pass

@cli.command()
@click.argument("name")
def hello(name):
    click.echo(f"hello, {name}")

Sourcing this in a python interpreter, hello can be invoked with an arg list:

>>> cli(["hello", "chris"])
hello, chris

Process finished with exit code 0

So the answer is: invoke the interface with an arg list. And the specific answer for my use case, defining short-circuit entrypoints in my module's automatic script section, can be enabled via the following technique:

# cli.py 

def hello_fn():
  cli(["hello", "chris"]

# setuptools setup.py
setup( 
  ...
  entry_points = {
    'console_scripts': [
      "hello = myModule.cli:hello_fn",
      ...
    ]
  }