【问题标题】:How to 'self-invoke' python-click CLI commands without Context.invoke or Context.forward?如何在没有 Context.invoke 或 Context.forward 的情况下“自调用”python-click CLI 命令?
【发布时间】:2021-08-22 09:45:29
【问题描述】:

click 库不鼓励调用 click.forward 和 click.forward 函数来“自调用”CLI 命令。引用docs:

有时,从另一个命令调用一个命令可能会很有趣。这是 Click 通常不鼓励使用的模式,但仍有可能。为此,您可以使用 Context.invoke() 或 Context.forward() 方法。

但是,他们不提供替代品。

例如,假设我们想在执行假设的our_cli buy some_item 之前使用我们自己的 CLI 调用 our_cli get user-funds 来验证用户的资金。 如果不使用Context.invoke 或Context.forward,该怎么做?


PS:这不是关于使用invoke 和forward 函数的问题。这已经在这里讨论过了:link, link。

【问题讨论】:

  • 这类问题是基于意见的,通常与 SO 无关。但一般来说,Click 是介于命令行和 Python 代码之间的一层。如果你已经在执行 Python 代码了,为什么还想通过 Click 层返回,而你可以直接调用 Python 代码呢?因此,Click 编码人员为什么要花时间构建此功能?
  • 感谢您的建设性反馈@StephenRauch。我会根据您的评论修改问题。
  • 更新了@StephenRauch 的问题。它现在要求替代方案,而不是询问为什么不鼓励这样做。您已经在评论中暗示了这一点:“直接调用 Python 代码”。如果您想解释为什么这在答案中更好,我很乐意接受。

标签: python python-3.x command-line-interface python-click


【解决方案1】:

感谢@StephenRauch 提供了直接调用python 代码的提示。
这是一个简化的示例,展示了如何重构 Context.invoke 调用以直接调用 python 代码。

示例

假设我们在购买假设商品之前调用了 CLI 的 get-user-funds 命令来获取用户的预算。

import click

# E.g., assume the price and funds come from some API
def get_funds(user): return 100  
def get_price(item): return 50   

@click.group()
@click.pass_context
def our_cli(ctx): 
    # To simplify, assume that the CLI already knows the relevant user.
    ctx.obj = {"user": "Cindy"} 


@our_cli.command()
@click.argument("user")
def get_user_funds(user):
    # Normally we would use this command to print the funds 
    # of a user to stdout.
    funds = get_funds(user)
    click.echo(f"{funds=}")
    return funds


@our_cli.command()
@click.argument("item")
@click.pass_context
def buy_item(ctx, item):
    # This is the `invoke` call that we wish to refactor.
    funds = ctx.invoke(get_user_funds)
    if funds >= get_price(item):
        print(f"bought {item}")
    else:
        print("f{funds}")


if __name__ == "__main__":
    our_cli()

重构

除了调用Context.invoke获取资金,我们也可以直接调用python代码。
我们可以通过重写buy_item 来做到这一点:

@our_cli.command()
@click.argument("item")
@click.pass_context
def buy_item(ctx: click.Context, item: str):
    # Now we call python code directly.
    funds = get_funds(ctx.obj["user"])
    # Note that bypass the click.echo(f"{funds=}") call now. This
    #  is probably something we would like in this example.
    if funds >= get_price(item):
        print(f"bought {item}")
    else:
        print("f{funds}")

结束语

在这个例子中,重构非常简单。
我们已经有了一个可以直接调用的 python 函数(即get_funds)。
处理更复杂的代码时,您可能需要重新构建代码。
就我而言,除其他外,我必须将我想直接从 @click.command 带注释的函数调用的逻辑提取到普通的 python 函数。
之后,我可以将Context.invoke 调用替换为直接函数调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 2015-09-14
    • 2020-12-29
    • 2012-07-15
    相关资源
    最近更新 更多