I want to implement mycommand --version
using python click. I have something like this working but it feels kinda clunky.
@click.group(invoke_without_command=True, no_args_is_help=True)
@click.pass_context
@click.option('--version', 'version')
def cli(ctx, version):
if version:
ctx.echo(f'{sys.argv[0]} {__version__}')
ctx.exit()
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.
Click's echo() function will automatically strip ANSI color codes if the stream is not connected to a terminal. the echo() function will transparently connect to the terminal on Windows and translate ANSI codes to terminal API calls.
As it turns out, click
has a builtin decorator click.version_option
to accomplish this. The code now becomes:
@click.group()
@click.version_option(__version__)
@click.pass_context
def cli(ctx):
pass
You can use click.version_option
decorator to implement --version
option.
If your setup.py
like this and have version
click will read it automatically.
from setuptools import setup
setup(
name='application',
version='0.1',
py_modules=['application'],
install_requires=[
'Click',
],
)
The click.version_option
option without any argument will read version from setup.py
it.
@click.group(invoke_without_command=True, no_args_is_help=True)
@click.pass_context
@click.version_option()
def cli(ctx):
...
Run and Result
$ application --version
application, version 0.1
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