本文介绍了当我们使用click.group()时如何仅激活选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用click创建命令行参数.我几乎完成了研究,并且一切正常.问题是我想在使用click.group()而不是子命令时使用唯一的选项.

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.

让我们说myCommand --version这应该打印我的应用程序的版本,但是出现错误,提示Error: Missing command.

Lets say myCommand --version this should print my application's version but it's raising error saying Error: Missing command.

我的代码是:

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")

这里--version仅在我使用cli --version init之类的选项调用命令时有效,但是我希望它是cli --version来打印版本.

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.

有人可以帮我吗?

推荐答案

有一个click.version_option作为内置控件,应该可以执行您想要的操作.

There is a click.version_option available as a buillt in, which should do what you wanted.

版本选项的文档

但是,如果您想推出自己的实现,我认为您可以尝试将invoke_without_command=True添加到组声明中,如下所示:

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)

这篇关于当我们使用click.group()时如何仅激活选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 18:27