Python 如何在执行run()之前强制结构连接到远程主机?

Python 如何在执行run()之前强制结构连接到远程主机?,python,fabric,Python,Fabric,我正在使用fabric编写rsync包装,变量env.host_字符串将由execute()设置为运行任务。要获取env.host_字符串,我首先运行('pwd'),然后运行rsync 是否可以确保用户在某些检查点到达之前设置了env.hosts,例如条件src==env.host\u字符串 from fabric.api import run, env, task, abort from string import Template @task def sync_to_same_dir(sr

我正在使用fabric编写rsync包装,变量env.host_字符串将由execute()设置为运行任务。要获取env.host_字符串,我首先运行('pwd'),然后运行rsync

是否可以确保用户在某些检查点到达之前设置了env.hosts,例如条件src==env.host\u字符串

from fabric.api import run, env, task, abort
from string import Template

@task
def sync_to_same_dir(src, path):
    env.host_string
    cmd_template = Template("""rsync --dry-run -e ssh -avr $user@$src_host:$path/ $path/""")
    if path.endswith("/"):
        path = path[:-1]

    run("pwd") # it's a work around
    if src == env.host_string:
        abort("cannot rysnc to the same host")
    cmd = cmd_template.substitute(path=path, user=env.user, src_host=src)
    run(cmd)

我从fabric的源代码中找到了答案。有一个简单的想法:如何运行根据需要检查主机

@needs_host
def put(local_path=None, remote_path=None, use_sudo=False,
    mirror_local_mode=False, mode=None):
    """
    Upload one or more files to a remote host.
    """
我跟踪主机的需求,当用户未分配任何主机时,它将提示询问主机:

No hosts found. Please specify (single) host string for connection: 
我们可以将任务改写为:

from fabric.network import needs_host

@task
@needs_host
def the_task_needs_host(): pass

你想干什么?任务知道它正在使用的主机没有任何其他结构调用:

fab -f host-test.py foo
[98.98.98.98] Executing task 'foo'
98.98.98.98
98.98.98.98

Done.
下面是脚本,例如:

#!/user/bin/env python

from fabric.api import *

env.user = 'mgoose'

@task
@hosts("98.98.98.98")
def foo():
    print(env.host)
    print(env.host_string)

因此,您不必做任何特殊的事情来了解任务所在的主机。

谢谢您的回复,但我想确保在某些方法调用或检查点之前,已将用户设置为主机。我将改进我的问题。它只是python。所以检查:如果env.hosts不是None:;这就足够了。