Fabric python3什么是上下文,它必须包含什么,为什么需要传递它?

2024-06-02 04:29:54 发布

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

这是我的结构代码:

from fabric import Connection, task

server = Connection(host="usrename@server.com:22", connect_kwargs={"password": "mypassword"})

@task
def dostuff(somethingmustbehere):
    server.run("uname -a")

这个代码很好用。当我执行fab dostuff时,它会执行我希望它做的事情。在

但是,当我删除somethingmustbehere时,我收到以下错误消息:

^{pr2}$

我从未在代码中的任何地方定义somethingmustbehere。我只要把它放进去,错误就消失了,一切正常。但为什么呢?这个变量是什么?为什么我需要它?为什么这么重要?如果它如此重要,为什么它能空着呢?我真的迷路了。是的,它可以工作,但我不能运行我不理解的代码。它让我发疯。:-)

请注意,我说的是python3(!)面料版本! Fabric版本是2.4.0


Tags: 代码fromimport版本comhosttaskserver
1条回答
网友
1楼 · 发布于 2024-06-02 04:29:54

为了能够运行@task,您需要一个上下文参数。Fabric使用invoketask(),它希望看到一个上下文对象。通常我们将变量命名为cctx(我总是用它来让它更清楚)。我不喜欢使用c,因为我通常用它来连接

在github上从invoke package repo检查这个line,你会发现当上下文参数不存在时,它会引发一个异常,但它没有解释原因!在

要了解上下文对象的更多信息,它是什么以及我们为什么需要它,您可以在pyinvoke网站上阅读以下内容:

Aside: what exactly is this ‘context’ arg anyway? A common problem task runners face is transmission of “global” data - values loaded from configuration files or other configuration vectors, given via CLI flags, generated in ‘setup’ tasks, etc.

Some libraries (such as Fabric 1.x) implement this via module-level attributes, which makes testing difficult and error prone, limits concurrency, and increases implementation complexity.

Invoke encapsulates state in explicit Context objects, handed to tasks when they execute . The context is the primary API endpoint, offering methods which honor the current state (such as Context.run) as well as access to that state itself.

检查这两个链接:

老实说,我浪费了很多时间来弄清楚什么是上下文以及为什么没有上下文我的代码就不能运行。但在某个时候,我放弃了,开始使用它来运行代码而不出错。在

相关问题 更多 >