python - 在 Fabric 中,如何从另一个 python 文件执行任务?

标签 python fabric

我有一个声明了一些任务的 fabfile (fabfile.py):

# fabfile.py
from fabric.api import *

@task
def start():
  # code

@task
def stop():
  # code

然后,当我尝试使用 fabric 中的执行函数调用任何这些任务时,如下所示:

# main.py
from fabric.api import execute
from fabfile import * # I don't really know if this is necessary 
                      # or how should it be done
def main():
  execute('start')

它引发了这个错误:

Fatal error: None is not callable or a valid task name

我的意图是为 fabfile 中指定的一些任务制作一种包装器,可以用不同的参数调用,并且当你调用这个主程序时,要执行的任务必须从参数中获取,所以我不能显式调用函数,但使用任务名称。

这将如何完成?也许我误解了 Fabric 的工作原理?

谢谢

最佳答案

execute('start') 更改为 execute(start)

我没弄明白为什么传递一个任务名来执行不起作用,但有一个解决方法:

import fabfile
execute(getattr(fabfile, 'start'))

更新: 在阅读了一些代码并对结构进行了一些测试后,我认为 execute('task_name') 只能在加载结构任务时使用。默认情况下,您可以像这样在 fabfile.py 中使用它:

@task
def task1():
    #do task1

@task
def task2():
    #do task2

@task
def task3():
    #do task1 and task2
    execute('task1')
    execute('task2')

然后你可以使用fab task3来同时执行task1task2。但直到现在,我仍在使用 fabric 作为工具。

再次更新:-)

然后我读了一些 Fabric 的代码,发现 使用 fabric 作为工具将调用 fabric.main.main,它调用 fabric.main.load_fabfile 从 fabfile 加载任务。

由于您使用 python main.py 来运行您的脚本,因此即使您导入了 fabfile,也不会加载 fab 任务。所以我给你加了一点代码 main.py:

docstring, callables, default = load_fabfile('fabfile.py')
state.commands.update(callables)

现在,execute('start') 完全如您所愿。

关于python - 在 Fabric 中,如何从另一个 python 文件执行任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23605418/

相关文章:

Python编写AVRO时间戳-毫秒: datum. astimezone(tz = timezones.utc)AttributeError: 'int'对象没有属性 'astimezone'

python - Pandas 'DataFrame' 对象没有属性 'unique'

python - 导入错误 : No module named 'pip._vendor.diSTLib.scripts' when I try to install fabric by python pip

git - 在部署期间将 git 修订号插入文件

python - 警告 : Unable to load SSH config file '/root/.ssh/config' in fabric

python - 在产品存储库或外部存储库中构建/部署脚本?

python - 如何在多核上运行 Keras?

python - 如何在 GPU 上从 PyTorch 中的另外两个张量有条件地构造一个张量?

python - Pandas : Delete rows based on other rows

python - saltstack 可以做类似 Fabric 的事情吗?