我需要在Fabric中为每个调用设置一些环境变量,到目前为止,我正在做类似的事情:
env['FOO'] = 'one'
@task
def one():
env['FOO'] = 'one'
print(cyan('Using FOO %s' % env['FOO']))
@task
def two():
env['FOO'] = 'two'
print(cyan('Using FOO %s' % env['FOO']))
@task
def run():
with shell_env(FOO=env['FOO']):
local(...)
# more tasks that have the same pattern as run() above
首先,如果没有调用“一个”或“两个”,我想提供一个更好的自动设置FOO的机制。也许每次Fabric运行都会调用一些隐式的“设置”任务或方法?
此外,实际上有更多FOO设置(总共10个),是否在找不到任务时调用了通用任务/方法?有点喜欢的东西:
def catchall(name, *args, **kwargs):
if name in ['one', 'two', ...]:
env['FOO'] = name
答案 0 :(得分:1)
您可以将任务作为自定义类的子类,并使用作为参数传递的某些属性:
from fabric.api import task
from fabric.tasks import Task
class CustomTask(Task):
def __init__(self, func, *args, **kwargs):
super(CustomTask, self).__init__(*args, **kwargs)
self.func = func
self.foo = "one"
def run(self, *args, **kwargs):
return self.func(self.foo, *args, **kwargs)
@task(task_class=CustomTask)
def one(foo):
print(cyan('Using FOO %s' % foo))