Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement --version using python click?

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()
like image 739
wonton Avatar asked Nov 01 '19 23:11

wonton


People also ask

How do you use the click function in Python?

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.

What is Click option in Python?

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.

What is click echo in Python?

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.


2 Answers

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
like image 115
wonton Avatar answered Oct 16 '22 09:10

wonton


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
like image 1
EsmaeelE Avatar answered Oct 16 '22 10:10

EsmaeelE