gpt4 book ai didi

python - 如果调用特定子命令,则执行不同的父命令操作?

转载 作者:行者123 更新时间:2023-12-01 07:55:38 24 4
gpt4 key购买 nike

在正常情况下,我的应用程序会将一组配置值加载到上下文中,这些值将通过 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.pycli 函数中添加什么,这样我就不会尝试加载配置文件,当(且仅当)时,用户正在运行configcmd first-run?任何其他命令/子命令都要求此配置文件存在,因此我希望保留这些检查。

最佳答案

要在执行子命令之前调用某些特定代码(基于调用的特定子命令),您可以查看 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

关于python - 如果调用特定子命令,则执行不同的父命令操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55999396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com