Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我使用fabric,但很多都是with,所以我想使用python';让decorator使代码变得更好_Python_Decorator_Fabric - Fatal编程技术网

我使用fabric,但很多都是with,所以我想使用python';让decorator使代码变得更好

我使用fabric,但很多都是with,所以我想使用python';让decorator使代码变得更好,python,decorator,fabric,Python,Decorator,Fabric,基本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

基本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")
我想改变如下:

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主机,而基本代码不要求我输入主机,但更改后的代码应该这样做

请尝试以下代码:

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