您可以用过滤器替换标准输出(或任何 iostream),而不是修改/覆盖 Fabric。
这是一个覆盖 stdout 以审查特定密码的示例。它从 Fabric 的env.password
变量中获取密码,由-I
参数设置。请注意,您可以使用正则表达式执行相同的操作,这样您就不必在过滤器中指定密码。
我还应该提到,这不是世界上最高效的代码,但如果您使用的是结构,您可能会将一些东西粘合在一起,并且更关心可管理性而不是速度。
#!/usr/bin/python
import sys
import string
from fabric.api import *
from fabric.tasks import *
from fabric.contrib import *
class StreamFilter(object):
def __init__(self, filter, stream):
self.stream = stream
self.filter = filter
def write(self,data):
data = data.replace(self.filter, '[[TOP SECRET]]')
self.stream.write(data)
self.stream.flush()
def flush(self):
self.stream.flush()
@task
def can_you_see_the_password():
sys.stdout = StreamFilter(env.password, sys.stdout)
print 'Hello there'
print 'My password is %s' % env.password
运行时:
fab -I can_you_see_the_password
Initial value for env.password:
这将产生:
Hello there
My password is [[TOP SECRET]]