问题
I'm currently working to create Command line arguments with click. I almost done the research, and everything is working fine. The issue is I want to use the only option while working with the click.group()
other than sub commands.
Lets say myCommand --version
this should print my application's version but it's raising error saying Error: Missing command.
My code is:
import sys
import os as _os
import click
import logging
from myApp import __version__
@click.group()
@click.option('--version', is_flag=True, help="Displays project version")
@click.pass_context
def cli(context, version: bool):
if version:
print(__version__)
@cli.command()
@click.pass_context
def init(context):
click.echo(message="Starting initilization for the project" + str(context.obj))
@cli.command()
@click.pass_context
def install(context):
click.echo(message="Starting installing from the saved data")
Here --version is only working when I call the command with option like cli --version init
, But I want this to be cli --version
to print the version.
Can anyone help me with this?
回答1:
There is a click.version_option
available as a buillt in, which should do what you wanted.
Documentation for version option
However, if you want to roll your own implementation, I think you can try adding invoke_without_command=True
to your group declaration as such:
@click.group(invoke_without_command=True)
来源:https://stackoverflow.com/questions/60613170/how-to-activate-only-options-when-we-use-click-group