I would like to add unspecified options to the cli command using python-click library. So my cli function could look like the following
$ my-cmd --option1 value1 --options2 value2 --unknown_var value3
My current code:
import click
@click.option('--option1')
@click.option('--option2')
@click.command(name='my-cmd')
def cli(option1, option2):
click.echo("my test")
I would like to see something like the following:
import click
@click.option('--option1')
@click.option('--option2')
@click.command(name='my-cmd')
def cli(option1, option2, **kwargs):
click.echo("my test")
# Manually manage **kwargs
Python click option namesClick derives the name of the option from the long name, if both are used. In the example, we create an option with both short and long names. The name of the variable passed to the function is string , derived from the longer option name. We run the program using both option names.
Click is a Python package for creating beautiful command line interfaces in a composable way with as little code as necessary. It's the “Command Line Interface Creation Kit”. It's highly configurable but comes with sensible defaults out of the box.
Typer is a library for building Command Line Interface (CLI) applications based on Python's type hints. It is created by Sebastián Ramírez, the author of FastAPI. Typer is short to write and easy to use. To install Typer, type: pip install typer.
You can pass context
with ignore_unknown_options
and allow_extra_args
settings, the extra arguments will be collected in context.args
list (['--unknown_var', 'value3', '--unknown_var2', 'value4']
). Then you can transform it to dict.
import click
@click.command(name='my-cmd', context_settings=dict(
ignore_unknown_options=True,
allow_extra_args=True,
))
@click.option('--option1')
@click.option('--option2')
@click.pass_context
def cli(ctx, option1, option2):
click.echo({ctx.args[i][2:]: ctx.args[i+1] for i in range(0, len(ctx.args), 2)})
example
python cli.py --option1 value1 --option2 value2 --unknown_var value3 --unknown_var2 value4
>> {'unknown_var2': 'value4', 'unknown_var': 'value3'}
See Forwarding Unknown Options.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With