Python Click:如果设置了标志,则忽略丢失的参数错误

砂壤土

我想制作一个简单的 CLI 程序,该程序将接受--edit-config在编辑器中打开其配置的选项。但是,如果我--edit-config指定标志,我无法弄清楚如何使 Click 忽略缺少的参数错误

import click

@click.group(invoke_without_command=True)
@click.argument("name")
@click.option("--edit-config", is_flag=True)
def cli(name, edit_config):
    # If we run it like
    # $ myprog --edit-config | Missing Argument: NAME
    if edit_config:
        click.echo("Editing config")
        ...
        exit(0)
    
    # But this is the main functionality
    # $ myprog John
    click.echo(f"Hello, {name}")

@cli.command()
def command_a():
    ...
...

第一个命令导致 Missing Argument 错误。可以有变通方法,例如nargs=-1required=False,但是,这似乎使帮助页面要么完全运行要么name在帮助消息中将参数标记为可选,这在大多数用例中并非如此。

如果指定了某个选项,是否有一种简单的方法可以使 Click 不引发 Missing Argument 错误?

砂壤土

在进一步阅读文档后,我发现了这一节,它提供了一种实现方式--edit-config或任何其他完全改变执行流程的选项。

def edit_config(ctx, param, value):
    if not value or ctx.resilient_parsing:
        return
    click.echo("Editing config")
    ctx.exit()

@click.group(invoke_without_command=True)
@click.argument("name")
@click.option("--edit-config", is_flag=True, callback=edit_config,
              is_eager=True, expose_value=False)
def cli(name):
    print(f"Hello, {name}!")

@cli.command()
def howareyou():
    print(f"How are you?")
 $ myapp John
Hello, John!

 $ myapp John howareyou
Hello, John!
How are you?

 $ myapp --edit-config
Editing config

 $ myapp --help
Usage: myapp [OPTIONS] NAME COMMAND [ARGS]...

Options:
  --edit-config 
  --help         Show this message and exit.

Commands:
  howareyou

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

python object()没有参数错误

module .__ init __()在Python中最多接受2个参数错误

我无法传递参数错误:无法识别的参数:Argparse Python3

Python Class()没有参数错误。我正在使用Self

在python中读取json值时出现无效的参数错误

python:object()没有参数错误

使用MySQL Insert命令运行python时出现参数错误

运行rdkit.Chem.SaltRemover()时发生Python参数错误。(Python参数类型与C ++签名不匹配)

当只有一个时,Python抛出多个参数错误

JavascriptException:消息:javascript错误:arguments [0] .click不是使用arguments [0] .click通过Selenium和Python的函数错误

在VS代码中调试Python脚本时出现无法识别的参数错误

使用lamda函数错误的Python缺少1个必需的位置参数:'event'

参数错误行为docopt python

python:先验函数错误生成的参数

Python Winsound标志错误?

如果条件Python被忽略?

Python类参数错误

在python中使用“使用std :: vector”时出现SWIG参数错误

序数错误,Python 3

Mac下的Python 2子过程参数错误

Python多线程参数错误

当没有给出参数错误时,Python 类自变量作为默认值

python3类参数错误

如果我在字符串中传递 $ 作为输入参数,则 Python 参数丢失

使用 Python 访问 aws ecr 时的参数错误

Python PDF Randomizer 位置参数错误

如何将参数传递给python函数错误

Python 如果存在错误,则忽略并继续执行其余代码

Python中的语音识别错误(位置参数错误)