I have a function which is wrapped as a command using click. So it looks like this:
@click.command()
@click.option('-w', '--width', type=int, help="Some helping message", default=0)
[... some other options ...]
def app(width, [... some other option arguments...]):
[... function code...]
I have different use cases for this function. Sometimes, calling it through the command line is fine, but sometime I would also like to call directly the function
from file_name import app
width = 45
app(45, [... other arguments ...])
How can we do that? How can we call a function that has been wrapped as a command using click? I found this related post, but it is not clear to me how to adapt it to my case (i.e., build a Context class from scratch and use it outside of a click command function).
EDIT: I should have mentioned: I cannot (easily) modify the package that contains the function to call. So the solution I am looking for is how to deal with it from the caller side.
You can call a
click
command function from regular code by reconstructing the command line from parameters. Using your example it could look somthing like this:Code:
How does this work?
This works because click is a well designed OO framework. The
@click.Command
object can be introspected to determine what parameters it is expecting. Then a command line can be constructed that will look like the command line that click is expecting.Test Code:
Test Results:
I tried with Python 3.7 and Click 7 the following code:
All the
app
calls are working fine!