Skip to content
Advertisement

Use Python click command to invoke a class method with variadic arguments

I have a class that gets initialized with a previously unknown number of arguments and I want it to be done on CLI using Python’s click package. My issue is that I can’t manage to initialize it and run a click command:

JavaScript

Setting a defined number of arguments, like nargs=5, solves the issue of missing command but obligates me to input 5 arguments before my command. With variadic arguments like nargs=-1, click doesn’t recognize click_command as a command.

How can I input n-many arguments, and then run the command using click?

JavaScript

I expect to be able to run a click command after passing n-many args to my Foo() class, so I can initialize it and run its log() method as a CLI command, but the output is:

Error: Missing command

Advertisement

Answer

I am not entirely sure what you are trying to do is the best way to approach this problem. I would think that placing the variadic arguments after the command would be a bit more logical, and would definitely more align with the way click works. But, you can do what you are after with this:

Custom Class:

JavaScript

Using Custom Class:

Then to use the custom class, pass it as the cls argument to the group decorator like:

JavaScript

Test Code:

JavaScript

Results:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement