隐式调用python Fabric启动时的任务/函数吗? [英] Implicitly called task / function on python Fabric startup?

查看:98
本文介绍了隐式调用python Fabric启动时的任务/函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次调用我都需要在Fabric中设置一些环境变量,到目前为止,我正在做类似的事情:

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

首先,如果没有调用一个"或两个",我想提供一种更好的自动设置FOO的机制.也许每次Fabric运行时都会调用一些隐式的设置"任务或方法吗?

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?

此外,实际上还有更多的FOO设置(总共10个),是否在找不到任务时调用了通用任务/方法?像包罗万象的东西:

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))

这篇关于隐式调用python Fabric启动时的任务/函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆