如果调用了特定的子命令,是否执行不同的父命令操作?

2024-06-28 20:11:06 发布

您现在位置:Python中文网/ 问答频道 /正文

在正常情况下,我的应用程序会将一组配置值加载到上下文中,并将这些值传递给具有pass_context的子命令。只有一种情况下,这将无法工作-第一次运行应用程序和配置尚未设置。你知道吗

我的目标是允许用户运行一个子命令并生成适当的配置,以便CLI在其余时间工作。你知道吗

我的cli.py代码:

import sys
import click
from ruamel.yaml import YAML
from pathlib import Path

from commands.config_cmds import configcmd

MYAPP = "AwesomeCLI"

@click.group()
@click.version_option()
@click.pass_context
def cli(ctx):
    """command line application"""
    ctx.ensure_object(dict)
    ctx.obj['APPLICATION_NAME'] = MYAPP

    config_file = Path(click.get_app_dir(ctx.obj[MYAPP])) / "config.yml"
    yaml = YAML(typ="safe")
    try:
        config_yml = yaml.load(config_file)
    except FileNotFoundError:
        click.secho("Run command: awesome-cli configcmd first-run", fg='red')
        raise click.FileError(config_file.name, "Missing configuration file.")

    ctx.obj['CONFIG'] = yaml.dump(config_yml)


cli.add_command(configcmd)

我的configcmd代码:

@click.group()
def configcmd():
    """Manage configuration of this tool
    \f
    The configuration file is saved in $HOME/.config/awesome-cli
    """

@config.command()
@click.pass_context
def first_run(ctx):
    """
    Set up CLI configuration. 
    """
    api_key = click.prompt("Your API Key")
    # More stuff here about saving this file...

如果我运行python awesome-cli configcmd,我会收到以下错误(如预期的那样):

Run command: awesome-cli configcmd first-run
Error: Could not open file config.yml: Missing configuration file.

但是,如果我运行这个命令python awesome-cli configcmd first-run,我会收到相同的错误,这不是我的目标。很明显,我应该在这段代码中得到这个错误,但那是因为我不知道如何根据被调用的命令/子命令添加异常。你知道吗

我需要在cli.py中的cli函数中添加什么,这样当(并且仅当)用户正在运行configcmd first-run时,我就不会尝试加载配置文件了?任何其他命令/子命令都要求此配置文件存在,因此我希望保留对这些文件的检查。你知道吗


Tags: runimport命令configyamlcliymlconfiguration
1条回答
网友
1楼 · 发布于 2024-06-28 20:11:06

要在执行基于所调用的特定子命令的子命令之前调用某些特定代码,可以查看ctx.invoked_subcommand,如:

if ctx.invoked_subcommand != 'configcmd':

在您的示例中,您需要检查每个级别的ctx.invoked_subcommand,如:

测试代码:

import sys
import click
from ruamel.yaml import YAML
from pathlib import Path

MYAPP = "AwesomeCLI"

@click.group()
@click.pass_context
def cli(ctx):
    """command line application"""
    ctx.ensure_object(dict)
    ctx.obj['APPLICATION_NAME'] = MYAPP
    ctx.obj['CONFIG_FILEPATH'] = Path(click.get_app_dir(MYAPP), "config.yml")
    if ctx.invoked_subcommand != 'configcmd':
        load_config(ctx)

@cli.group()
@click.pass_context
def configcmd(ctx):
    """Configuration management for this CLI"""
    click.echo("In config")
    if ctx.invoked_subcommand != 'first-run':
        load_config(ctx)

def load_config(ctx):
    yaml = YAML(typ="safe")
    try:
        config_yml = yaml.load(ctx.obj['CONFIG_FILEPATH'])
    except FileNotFoundError:
        click.secho("Run command: awesome-cli configcmd first-run",
                    fg='red')
        raise click.FileError(str(ctx.obj['CONFIG_FILEPATH']),
                              "Missing configuration file.")

    ctx.obj['CONFIG'] = yaml.load(config_yml)


@configcmd.command('first-run')
@click.pass_context
def first_run(ctx):
    """Set up CLI configuration."""
    click.echo("In first-run")

@configcmd.command('test-cmd')
@click.pass_context
def test_cmd(ctx):
    """ This command will not be reachable without config file"""
    click.echo("In first-run")


if __name__ == "__main__":
    commands = (
        'configcmd first-run',
        'configcmd test-cmd',
        'configcmd  help',
        ' help',
        '',
    )

    import sys, time

    time.sleep(1)
    print('Click Version: {}'.format(click.__version__))
    print('Python Version: {}'.format(sys.version))
    for cmd in commands:
        try:
            time.sleep(0.1)
            print('     -')
            print('> ' + cmd)
            time.sleep(0.1)
            cli(cmd.split())

        except BaseException as exc:
            if str(exc) != '0' and \
                    not isinstance(exc, (click.ClickException, SystemExit)):
                raise

结果:

Click Version: 6.7
Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
     -
> configcmd first-run
In config
In first-run
     -
> configcmd test-cmd
In config
Run command: awesome-cli configcmd first-run
Error: Could not open file C:\Users\stephen\AppData\Roaming\AwesomeCLI\config.yml: Missing configuration file.
     -
> configcmd  help
Usage: test.py configcmd [OPTIONS] COMMAND [ARGS]...

  Configuration management for this CLI

Options:
   help  Show this message and exit.

Commands:
  first-run  Set up CLI configuration.
  test-cmd   This command will not be reachable without...
     -
>  help
Usage: test.py [OPTIONS] COMMAND [ARGS]...

  command line application

Options:
   help  Show this message and exit.

Commands:
  configcmd  Configuration management for this CLI
     -
> 
Usage: test.py [OPTIONS] COMMAND [ARGS]...

  command line application

Options:
   help  Show this message and exit.

Commands:
  configcmd  Configuration management for this CLI

相关问题 更多 >