使用atexit进行织物清理操作

时间:2013-07-14 16:18:57

标签: python fabric atexit

在结构任务中是否有关于如何清理(例如删除临时文件等)的智慧?如果我像往常一样使用atexit模块,那么我很难,因为我不能使用@roles装饰器来装饰传递给atexit.register()的函数。或者我可以吗?其他面料用户如何处理这个?

1 个答案:

答案 0 :(得分:5)

我也有同样的问题。下一个代码并不理想,但我目前有这样的实现。

fabfile.py

from functools import wraps
from fabric.network import needs_host
from fabric.api import run, env

def runs_final(func):
    @wraps(func)
    def decorated(*args, **kwargs):
        if env.host_string == env.all_hosts[-1]:
            return func(*args, **kwargs)
        else:
            return None
    return decorated

@needs_host
def hello():
    run('hostname')
    atexit()

@runs_final
def atexit():
    print ('this is at exit command.')

结果:

fabric$ fab hello -H web01,web02
>[web01] Executing task 'hello'
>[web01] run: hostname
>[web01] out: web01
>[web01] out: 
>[web02] Executing task 'hello'
>[web02] run: hostname
>[web02] out: web02
>[web02] out: 
>
>this is at exit command.
>
>Done.
相关问题