4

我需要通过打开和读取文件以获取主机来设置其主机列表。以这种方式设置它可以让我拥有大量主机列表,而无需每次都为这些数据编辑我的 fabfile。

我试过这个:

def set_hosts():
    env.hosts = [line.split(',') for line in open("host_file")]

def uname():
    run("uname -a")

def set_hosts():
    env.hosts = open('hosts_file', 'r').readlines

def uname():
    run("uname -a")

每次尝试使用函数 set_hosts 时都会出现以下错误:

fab set_hosts uname
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/fabric/main.py", line 712, in main
    *args, **kwargs
  File "/usr/local/lib/python2.7/dist-packages/fabric/tasks.py", line 264, in execute
    my_env['all_hosts'] = task.get_hosts(hosts, roles, exclude_hosts, state.env)
  File "/usr/local/lib/python2.7/dist-packages/fabric/tasks.py", line 74, in get_hosts
    return merge(*env_vars)
  File "/usr/local/lib/python2.7/dist-packages/fabric/task_utils.py", line 57, in merge
    cleaned_hosts = [x.strip() for x in list(hosts) + list(role_hosts)]
AttributeError: 'builtin_function_or_method' object has no attribute 'strip'
4

1 回答 1

15

您在这里遇到的问题是您将 env.hosts 设置为函数对象,而不是列表或可迭代对象。您需要 readlines 之后的括号,才能实际调用它:

def set_hosts():
    env.hosts = open('hosts_file', 'r').readlines()
于 2012-04-30T22:38:26.787 回答