When using the python click library to create command-line tools, is it possible to pass an unknown number of arguments to a function? I am thinking of something similar to the *args command.
I am trying to build a wrapper for catkin and would like to use click for all the nice utilities it comes with. This application should perform some tasks, like changing into the root of the workspace, before calling catkin with the specified command. E.g. catkin build
to compile the code.
The problem with this is, that I do not want to explicitly declare every possible compile flag that you can pass to catkin but rather want to only look out for the actual command and pass all the arguments directly to catkin.
What I have found so far, is the possibility to define a last argument with the option nargs=-1
which will collect all succeeding arguments in this variable. This way you can collect for example a couple of file names. This is almost what I am looking for, except that it wont take flags beginning with a dash -
. It will from an error saying Error: no such option: -a
#!/usr/bin/python
import click
import subprocess
@click.command()
@click.argument('action', type=click.STRING)
@click.option('--debug', is_flag=True, help='Build in debug mode.')
@click.argument('catkin_args', nargs=-1, type=click.STRING)
def main(action, debug, catkin_args):
""" A wrapper for catkin """
# Do something here ...
if debug:
# Do some more special things...
subprocess.call(["catkin"] + catkin_args)
According to the docs it's possible in click 4.0+; you just need to set the type
of your catkin_args
to click.UNPROCESSED
.
Documentation has an example wrapping timeit
like you describe you want to do with catkin.