How to activate only options when we use click.group()

[亡魂溺海] 提交于 2020-04-16 02:57:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!