我希望有人能帮我解决这个问题。所以它看起来很简单,我只想获得在Fabric任务中设置的变量,并希望在另一个函数中调用它。全局变量似乎不起作用,我对python结构相对较新,所以任何帮助将不胜感激。
from fabric.api import *
@task
def function_inside(name):
samplename = name.lower()
print("{}".format(samplename))
def another_function():
print "This is outside: " + samplename
another_funtion()
因此,经过很多时间研究我的这个入门脚本,我只是有一个解决方法。
from fabric.api import *
container={A:'',B:''}
@task
def first_func(var):
container['A']=var
@task
def second_func(var):
container['B']=var
@task
def main_func():
var1=container['A']
var2=container['B']
print "This is from first function: " + var1
print "This is from second function: " + var2
所以当我执行结构时它会像这样:
fab firs_func:John second_func:Angel main_func
但这仍然是一种解决方法,我仍然想知道如何从任务中调用变量并将其传递给不是任务的正常函数。
答案 0 :(得分:0)
我不了解面料,但我可以帮助您获取全局变量
试试这个: -
def function_inside(name):
global samplename
samplename = name.lower()
print("{}".format(samplename))
def another_function():
print ("This is outside: " + samplename)
#execute as below
function_inside("HELLO")
another_function()
答案 1 :(得分:0)
我建议你添加你的"全球" Fabric的env
字典中的变量。这个字典在Python脚本的生命周期中保持其状态。鉴于此,您的代码将如下所示:
from fabric.api import *
from fabric.tasks import execute #The 'execute' function is quite useful
when you want to tell Fabric to execute a
function as a Fabric task
#No need to annotate your function
def function_inside(name):
env.samplename = name.lower()
print("{}".format(env.samplename))
def another_function():
print "This is outside: " + env.samplename
execute(function_inside, "Foo")
execute(another_function)
然后,在你的shell中:
python your_script.py
答案 2 :(得分:0)
如何同步运行任务并等待结果呢?
# @task
def first_func(var):
# process var
return var
# @task
def second_func(var):
# process var
return var
@task
def main_func():
var1=first_func(container['A'])
# or var1=first_func(var1)
var2=second_func(container['B'])
# or var2=first_func(var2)
print "This is from first function: " + var1
print "This is from second function: " + var2