【问题标题】:How to iterate a variable in fabric ssh?如何迭代fabric ssh中的变量?
【发布时间】:2016-12-17 03:36:51
【问题描述】:

例如:

global count
count += 1
@task
def install(hosts, local_swift_config):
    env.use_ssh_config = True
    env.hosts = set_hosts(hosts)
    execute(place_count)

def place_count():
    sudo('echo {} > /home/user/some_count'.format(count))
    count += 1

它不一定是全局的,用织物做这件事的首选方法是什么?

【问题讨论】:

    标签: python ssh fabric


    【解决方案1】:
    count = 0
    @task
    def install(hosts, local_swift_config):
        env.use_ssh_config = True
        env.hosts = set_hosts(hosts)
        execute(place_count)
    
    def place_count():
        sudo('echo {} > /home/user/some_count'.format(count))
        global count
        count += 1
    

    我已经为织物中的简单功能完成了这项工作。您的问题在于 python 全局变量,而不是结构。

    有关全局变量的更多信息,请参阅此线程:Stacokverflow Python Globals

    【讨论】:

    • 谢谢,我决定不使用global,而是改用env 变量。感谢您的提醒。我以前从未使用过全局变量,现在我会以牺牲良好实践为代价使用任何有效的方法。
    【解决方案2】:

    我决定不使用global

    def counter():
        env.count += 1
        if env.count == 2:
            env.count += 4
    
    @task
    def install(hosts):
        env.count = 0
    
        execute(counter)
        print(env.count)
    
        execute(counter)
        print(env.count)
    
        execute(counter)
        print(env.count)
    

    输出:

    1
    6
    7
    
    Done.
    

    【讨论】:

      猜你喜欢
      • 2020-01-16
      • 2010-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多