2014-09-01 56 views
-4

基地Python代碼:我用的面料,但很多有,所以我想使用Python的裝飾,使這個代碼更

for host in hosts: 
    with settings(
        host=host, 
        user=user, 
        password=passwd,`enter code here` 
       ): 
     run('uname -a') 

我想改變象下面這樣:

def take_with_out(host, user, password): 
with settings(
       host=host, 
       user=user, 
       password=passwd): 
    def dec(fn): 
     def wrapper(*argv, **kwgs): 
      fn(*argv, **kwgs) 
     return wrapper 
    return dec 

@take_with_out(host, user, password) 
def foo(command): 
    run(command) 

foo("uname -a") 

錯誤消息是讓我輸入主機以確保fabrice ssh主機,而基本代碼不問我主機,但更改的代碼應該。

回答

1

試試這個代碼:

class add_context(object): 
    def __init__(self, host, user, password): 
     self.host = host 
     self.user = user 
     self.password = password 

    def __call__(self, function): 
     def wrapped_function(*args,**kwargs): 
      with settings(host=self.host, user=self.user, password=self.password): 
       return function(*args, **kwargs) 
     return wrapped_function 

@add_context("localhost","unknow","password") 
def foo(command): 
    run(command) 

foo("uname -a") 
相關問題