gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:55:53 25 4
gpt4 key购买 nike

我有一个声明了一些任务的 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/

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