There are a few environment variables I need to set in Fabric each invocation and so far I'm doing something like:
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
Firstly, I would like to provide a better mechanism of auto setting FOO if neither 'one' or 'two' is invoked. Perhaps there's some implicit "set-up" task or method that is invoked every Fabric run?
Also, there are actually more FOO settings (10 in total), is there a generic task/method called when a task isn't found? Something like a catch-all like:
def catchall(name, *args, **kwargs):
if name in ['one', 'two', ...]:
env['FOO'] = name
解决方案
You can make your task a subclass of a custom class with certain attributes that are passed as parameters:
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))